[英]Python crypt module
当我发现一些名为“crypt”的东西时,我正在查看python模块。 我不明白。 我试过阅读这个,这个“盐”是什么,这个crypt模块的用途是什么,是否有某种方法可以将'crypt'应用于这段python代码?:
import crypt
max_attempts = 3
attempt = 0
try:
while attempt < max_attempts:
uname = input('Username: ')
password = input('pass: ')
if uname == 'admin' and password == 'Khs9':
print('Welcome Admin')
break
else:
attempt += 1
if attempt == max_attempts:
raise RuntimeError("\nYou've reached the maximum number of attempts allowed.")
else:
print('Wrong credentials.\n Try again or press <ctrl+c> to exit.\n')
continue
except KeyboardInterrupt:
print('Terminated by the user.\nGood-bye.')
except RuntimeError as e:
print("Goodbye")
现在我已经看到你的代码,我知道密码是'Khs9',我可以登录你的盒子。
您可以私下运行以下内容。
>>> crypt.crypt('Khs9', 'aa')
'aa0GPiClW35DQ
现在您更新代码:
import crypt
max_attempts = 3
attempt = 0
stored_pw_hash = 'aa0GPiClW35DQ'
try:
while attempt < max_attempts:
uname = input('Username: ')
entered_pw_hash = crypt.crypt(input('pass: '), stored_pw_hash)
if uname == 'admin' and entered_pw_hash == stored_pw_hash:
print('Welcome Admin')
break
else:
attempt += 1
if attempt == max_attempts:
raise RuntimeError("\nYou've reached the maximum number of attempts allowed.")
else:
print('Wrong credentials.\n Try again or press <ctrl+c> to exit.\n')
continue
except KeyboardInterrupt:
print('Terminated by the user.\nGood-bye.')
except RuntimeError as e:
print("Goodbye")
现在,如果您的代码泄露,他们就无法立即访问。 您应该有足够的时间意识到自己被黑了,然后更改密码。
这是背景信息......
crypt.crypt(密码)将返回密码的哈希值。 您存储哈希而不是明文密码。 这样,您就不会丢失密码给黑客,因为您没有密码。 丢失哈希不是一个大问题,因为它不保证访问(如果你遵循最佳实践,包括使用盐)。
下次有人提供密码时,你会计算它的哈希值,将它与之前存储的哈希值进行比较,如果它们匹配,你知道它们会给你正确的密码。
你为什么需要用盐? 因为有人花了很长时间来生成一个包含常用密码和哈希值的表。 完成后,可以快速检查哈希值。 通过使用salt,您可以确保应用不同的查找表,其中一个可能不可用,并且普通黑客没有时间生成它。
crypt.crypt()需要两个字符作为salt使用。 您可以将它传递给两个字符串或使用该函数的上一个输出。 (crypt.crypt()返回一个字符串,前两个字符为salt,其余为哈希)
我查看了https://docs.python.org/3.4/library/crypt.html来回答这个问题。
首先,请阅读Thomas Pornin关于如何安全地散列密码的规范答案 。 这将回答您关于“盐”的问题。
其次,地穴是一种古老而古老的算法 - 不要使用它。 即使是基于Python SHA-512的crypt也可能无法使用,因为您无法控制迭代次数(BCrypt可能称之为工作因素),因此您无法通过增加迭代次数来使其更安全。
第三, Python的3.4版具有基于OpenSSL内置的快速PBKDF2 。
这两个都支持hashlib内置的合理哈希类型! 请改用它们! 如何使用这些的一个例子是:
import hashlib
BinaryOutput = hashlib.pbkdf2_hmac('sha512',password, salt, args.iterations, args.outputBytes)
哪里
args.iterations在数十万到数万之间
args.outputBytes不超过64,假设使用SHA-512(其他算法较少),且不少于20。
以明文形式存储存储中的迭代次数(无论是硬编码,文件还是数据库),以便以后轻松地将其变大。
要获得盐,您应该生成至少12个,最好是至少16个加密随机字节。 为每个用户名添加不同的盐,并将其以明文形式存储在存储中(无论是硬编码,文件还是数据库)。
使用PBKDF2-HMAC-SHA-512使用64位操作,这可以降低基于GPU的攻击者对您的优势。
如果您担心定时攻击,可以使用各种常数时间比较之一。 与高迭代PBKDF2-HMAC-SHA-512相比,不会花费太多成本的是:
if hashlib.sha256(args.expectedBinary).hexdigest() == hashlib.sha256(BinaryOutput).hexdigest():
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.