关于密码加密的一点思路

关于密码加密的一点思路

如何在数据库被劫持代码泄露的情况下,用户密码依然不会被破解呢

带着这个问题我书写了一下代码

from hashlib import sha256, sha512

test_pwd = 'testpassword123'


class CipherHandler(object):
    """
    密码加密与密码比对
    """
    # 密码盐
    salt = "cvbjd%*vfjkse#fuei"

    @classmethod
    def encrypt(cls, pwd: str) -> str:
        """
        先随机加盐,再用两次sha256/sha512加密
        :return:
        """
        import random
        randnum = random.randint(1, 3)
        if randnum == 1:
            salt_pwd = ''.join([cls.salt, pwd])
            return cls._encryption(salt_pwd)

        elif randnum == 2:
            salt_pwd = ''.join([pwd, cls.salt])
            return cls._encryption(salt_pwd)

        elif randnum == 3:
            pwd_list = list(pwd)
            pwd_list.insert(randnum, cls.salt)
            salt_pwd = ''.join(pwd_list)

            return cls._encryption(salt_pwd)

    @classmethod
    def compare(cls, user_input_pwd: str,
                database_storage_pwd: str
                ) -> bool:
        """
        加密比对
        :return:
        """
        pwd_list = []

        salt_pwd_one = ''.join([cls.salt, user_input_pwd])
        pwd_list.append(cls._encryption(salt_pwd_one))

        salt_pwd_two = ''.join([user_input_pwd, cls.salt])
        pwd_list.append(cls._encryption(salt_pwd_two))

        str_list = list(user_input_pwd)
        str_list.insert(3, cls.salt)
        salt_pwd_three = ''.join(str_list)
        pwd_list.append(cls._encryption(salt_pwd_three))

        if database_storage_pwd not in pwd_list:
            return False
        return True

    @classmethod
    def _encryption(cls, salt_pwd: str) -> str:
        one_encryption = sha512((salt_pwd).encode('utf-8')).hexdigest()
        enc_pwd = sha512((one_encryption).encode('utf-8')).hexdigest()
        return enc_pwd


# 加密
print(CipherHandler.encrypt(test_pwd))

# 校验比对
print(CipherHandler.compare(test_pwd,'32b5b701ece1747eb90935fa55fe96983126a9683dbb1a537750fe5527eb3552ce13d31e2d2fad07fd8fe755794973221404e3a528dfa74ff0aff93e8b6745c6'))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值