gpt4 book ai didi

ubuntu - Python 3,Scrypt 模块,哈希不匹配

转载 作者:行者123 更新时间:2023-12-04 18:34:48 25 4
gpt4 key购买 nike

使用:Python 3.2.3、scrypt 0.5.5 模块、Ubuntu 12.04

我很好地安装了 scrypt 模块。我很好地在页面上运行了示例代码。我还找到了 expanded version of the sample code ,这也很好。但是我想测试它是否会两次对同一个单词进行哈希处理,所以我添加了一个对 Encrypt() 的部分调用,以模拟对数据库进行一次哈希处理然后在用户登录时再次进行哈希处理的概念,所以我的完整代码看起来像这样:

import random,scrypt

class Encrypt(object):

def __init__(self):
pass

def randSTR(self,length):
return ''.join(chr(random.randint(0,255)) for i in range(length))

def hashPWD(self,pwd, maxtime=0.5, datalength=64):
return scrypt.encrypt(self.randSTR(datalength), pwd, maxtime=maxtime)

def verifyPWD(self,hashed_password, guessed_password, maxtime=0.5):
try:
scrypt.decrypt(hashed_password, guessed_password, maxtime)
return True
except scrypt.error:
return False

if __name__ == '__main__':
e = Encrypt()
user_pw = 'theansweris42'
user_salt = 't9'
pw_salt = user_pw + user_salt
hashed_pw = e.hashPWD(pw_salt) # To be stored len()==192
y = e.verifyPWD(hashed_pw, pw_salt) # True
n = e.verifyPWD(hashed_pw, 'guessing'+ pw_salt) # False
print(y)
print(n)
#print("Hash: %s" % (hashed_pw))

x = Encrypt()
user_pw2 = 'theansweris42'
user_salt2 = 't9'
pw_salt2 = user_pw2 + user_salt2
hashed_pw2 = x.hashPWD(pw_salt2) # To be stored len()==192
y2 = x.verifyPWD(hashed_pw, hashed_pw2) # True
print(y2)
print(pw_salt)
print(pw_salt2)
print(hashed_pw)
print(hashed_pw2)

...如您所见,我还对盐进行了硬编码(用于测试)。奇怪的是,每次我运行它时, hashed_pw 和 hashed_pw2 总是不同的。为什么每次对相同的密码进行不同的哈希处理?每次我给它完全相同的输入时,它不应该输出相同的哈希吗?我一直在尝试解决这个问题一个小时,所以我想我最好问一下。

最佳答案

您使用相同的密码(加上盐)加密两个不同的随机字符串。这将导致两个不同的输出。

这里使用的技巧是密码+盐可用于解密该随机字符串,而错误的密码会引发错误。因此,您不需要存储原始随机字符串以确保密码正确,并且由于使用的字符串是随机的(在随机数生成器的限制内),因此破解密码将非常困难。

关于ubuntu - Python 3,Scrypt 模块,哈希不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11787120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com