import hashlib
def encrypt_password(password, salt):
# 创建一个sha256的哈希对象
sha256_hash = hashlib.sha256()
# 将盐值和密码组合起来并进行哈希
hashed_password = salt.encode('utf-8') + password.encode('utf-8')
sha256_hash.update(hashed_password)
# 获取哈希结果
encrypted_password = sha256_hash.hexdigest()
return encrypted_password
def verify_password(password, salt, encrypted_password):
# 对输入的密码进行加盐加密
new_encrypted_password = encrypt_password(password, salt)
# 比较加密后的密码和存储的加密密码是否一致
if new_encrypted_password == encrypted_password:
return True
else:
return False
if __name__ == "__main__":
password = input("Enter your password: ")
# 生成盐值
salt = 'yanzhi'
# 加密密码
encrypted_password = encrypt_password(password, salt)
print("Encrypted password:", encrypted_password)
# 验证密码
entered_password = input("Enter password again: ")
if verify_password(entered_password, salt, encrypted_password):
print("Password is correct")
else:
print("Password is incorrect")
标签:hashlib,sha256,加密,Python,encrypted,密码,password,salt
From: https://www.cnblogs.com/jessecheng/p/17547585.html