我想要一个Python程序,它输入一个密码和一个哈希(一种哈希),将密码转换为哈希并验证它是否等于之前给定的哈希。 我使用 ChatGPT 来回答我的问题,这里是代码:
import hashlib
def verify_password(password, hash_value):
algorithm, iterations, salt, hashed_password = hash_value.split(':')
iterations = int(iterations)
new_hash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt.encode('utf-8'), iterations).hex()
if hashed_password == new_hash:
return True
else:
return False
stored_hash = input("Give your hash : ")
user_password = input("Give your password : ")
print("Password hash is :", stored_hash)
# Verify
if verify_password(user_password, stored_hash):
print("Valid Password.")
else:
print("Wrong password.")
这里是我的“测试”密码的哈希示例:
:pbkdf2:sha512:30000:64:OSn313BE8n6uRs2ddby4EQ==:vkWCj+mYOfSMiKPm7ca+u4zBWPqzb4MmAcGJhAkhG02wssTdGuEKuSPFpVXK9cgfN2mdxLata/zL3UZcqUfDMA==
我尝试了该程序,我现在在哪里:
Give your hash : :pbkdf2:sha512:30000:64:OSn313BE8n6uRs2ddby4EQ==:vkWCj+mYOfSMiKPm7ca+u4zBWPqzb4MmAcGJhAkhG02wssTdGuEKuSPFpVXK9cgfN2mdxLata/zL3UZcqUfDMA= =
Give your password : testing*
Password hash is : :pbkdf2:sha512:30000:64:OSn313BE8n6uRs2ddby4EQ==:vkWCj+mYOfSMiKPm7ca+u4zBWPqzb4MmAcGJhAkhG02wssTdGuEKuSPFpVXK9cgfN2mdxLata/zL3UZcqUfDMA==
Traceback (most recent call last):
File "c:\Users\mathy\Downloads\temp.py", line 22, in <module>
if verify_password(user_password, stored_hash):
File "c:\Users\mathy\Downloads\temp.py", line 4, in verify_password
algorithm, iterations, salt, hashed_password = hash_value.split(':')
ValueError: too many values to unpack (expected 4)
我是 https://github.com/WolfgangFahl/py-3rdparty-mediawiki 的提交者,并已在 https://github.com/WolfgangFahl/py-3rdparty-mediawiki/blob/master/ 完成您的工作wikibot3rd/sso.py
进行工作测试。 在创建解决方案时仍然有 ChatGPT-4 支持,因此我不会发布完整的代码。问题是提示 ChatGPT 确保不同部分得到真正检查。 例如
if pbkdf2_indicator != "pbkdf2":
raise ValueError("verify_password expects pbkdf2 hashes")
并确保使用哈希算法:
new_hash = hashlib.pbkdf2_hmac(
hash_algorithm, password.encode("utf-8"), salt, iterations
)
您的问题中是硬编码的