[英]Python: hashed and verified passwords are not the same
我使用 hash_password function 到 hash 我的密码:
def hash_password(self):
os_urandom_static = b"ID_\x12p:\x8d\xe7&\xcb\xf0=H1\xc1\x16\xac\xe5BX\xd7\xd6j\xe3i\x11\xbe\xaa\x05\xccc\xc2\xe8K\xcf\xf1\xac\x9bFy(\xfbn.`\xe9\xcd\xdd'\xdf`~vm\xae\xf2\x93WD\x04"
salt = hashlib.sha256(os_urandom_static).hexdigest().encode('ascii')
pwdhash = hashlib.pbkdf2_hmac('sha512', self.password.encode('utf-8'), salt, 100000)
pwdhash = binascii.hexlify(pwdhash)
return (salt + pwdhash).decode('ascii')
为了验证密码,我使用 verify_password,我在 function 的末尾添加了 2 个打印来检查密码,它们不一样。 问题出在哪里?
def verify_password(self, stored_password, provided_password):
salt = stored_password[:64]
stored_password = stored_password[64:]
pwdhash = hashlib.pbkdf2_hmac('sha512', provided_password.encode('utf-8'), salt.encode('ascii'), 100000)
pwdhash = binascii.hexlify(pwdhash).decode('ascii')
print(pwdhash )
print(stored_password)
return pwdhash == stored_password
为我工作。 但是为什么要把事情复杂化呢?
相反,您可以将存储的密码与提供的密码的 hash 进行比较。
import hashlib, binascii
def hash_password(password):
os_urandom_static = b"ID_\x12p:\x8d\xe7&\xcb\xf0=H1\xc1\x16\xac\xe5BX\xd7\xd6j\xe3i\x11\xbe\xaa\x05\xccc\xc2\xe8K\xcf\xf1\xac\x9bFy(\xfbn.`\xe9\xcd\xdd'\xdf`~vm\xae\xf2\x93WD\x04"
salt = hashlib.sha256(os_urandom_static).hexdigest().encode('ascii')
pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt, 100000)
pwdhash = binascii.hexlify(pwdhash)
return (salt + pwdhash).decode('ascii')
stored_password = hash_password("Hello_World123")
print(stored_password)
def verify_password(stored_password, provided_password):
salt = stored_password[:64]
stored_password = stored_password[64:]
pwdhash = hashlib.pbkdf2_hmac('sha512', provided_password.encode('utf-8'), salt.encode('ascii'), 100000)
pwdhash = binascii.hexlify(pwdhash).decode('ascii')
print(pwdhash )
print(stored_password)
return pwdhash == stored_password
def verify_password_simple(stored_password, provided_password):
return stored_password == hash_password(provided_password)
print("verify_password:", verify_password(stored_password, "Hello_World123"))
print("verify_password_simple:", verify_password_simple(stored_password, "Hello_World123"))
print("verify_password_simple:", verify_password_simple(stored_password, "Bad PW"))
Output:
af756be6069a4bc6b3cfc0ec42aa757ae70395852ff7cacda38d1ab7ba890a896aa3f98243946e4c5910a6317dc1e9d6f1e46b314aab9b038a00ae34dcc9b0887ace6b72a9363974c403372aa93276328091259ee4584e4a7ee950f47dc7d0e4
6aa3f98243946e4c5910a6317dc1e9d6f1e46b314aab9b038a00ae34dcc9b0887ace6b72a9363974c403372aa93276328091259ee4584e4a7ee950f47dc7d0e4
6aa3f98243946e4c5910a6317dc1e9d6f1e46b314aab9b038a00ae34dcc9b0887ace6b72a9363974c403372aa93276328091259ee4584e4a7ee950f47dc7d0e4
verify_password: True
verify_password_simple: True
verify_password_simple: False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.