我必须对我正在参加的课程项目实施安全措施,但遇到了意料之外的事情。
首先,我存储了密码:
########################## Password hashing ############################
# 1. Generate salt
salt = os.urandom(32)
salt = (binascii.hexlify(salt)).decode('utf-8')
# 2. Append salt to the password
password = data['password']
password = password + salt
# 3. Hash the password and storing
password = bcrypt.generate_password_hash(password).decode('utf-8')
output_msg = database_helper.save_new_user(data['email'], password, data['firstname'], data['familyname'], data['gender'], data['city'], data['country'], salt)
########################################################################
这是保存在数据库中的数据:
[email protected]|$2b$12$WJx.XLYk/8Zx4HdDnPqxK.0RiZ6QR8rQEpZrw7jBpJRFUZ2sfBWyW|salt2|sal|male|link |swe|b5e333e0bae505d4fae6d9b993bcdcfd6964e480ce4dc1b5fd6b13c034d23bb8
为了进行密码验证,请执行以下操作:
########################### Password validation ############################
# 1. Retrive user's salt from the database
authentication_data = database_helper.get_users_salt(email)
# 2. Append salt to the inputed password and hash it
inputed_password = inputed_password + authentication_data['salt']
inputed_password = bcrypt.generate_password_hash(inputed_password).decode('utf-8')
# 3. Compare the hash generated from the inputed password with the one in
# the database
boolean_success = database_helper.check_user_password(email, inputed_password)
############################################################################
并且从数据库中获取盐显示结果,这就是我存储的内容:
b5e333e0bae505d4fae6d9b993bcdcfd6964e480ce4dc1b5fd6b13c034d23bb8
然后用盐对inputed_password进行哈希处理,结果表明:
$2b$12$yEE.OX5IFyIXTK4x3XOBbO4Ospm2hcCz9FCmjzEn3tC5DNg9crtxy
简而言之,为什么显示不同的哈希结果?
这不能回答您的代码出了什么问题,因为我看不到全部。但是,就其价值而言,这就是我使用bcrypt
创建和验证密码的方法:
创建:
# password entered by user
hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
hashed_str = hashed.decode('ascii')
# store out hashed_str for user
Validate:
# retrieve hashed_str for user
# password entered by user
valid = bcrypt.checkpw(password.encode('utf-8'), hashed_str.encode('ascii'))
注
bcrypt
仅处理不超过72个字节的密码,任何其他字符都将被忽略。因此,如果允许密码的编码长度超过72个字节,则可能需要使用以下代码:
创建:
# password entered by user
password_bytes = password.encode('utf-8')
if len(password_bytes) > 72:
password_bytes = base64.b64encode(hashlib.sha256(password_bytes).digest())
hashed = bcrypt.hashpw(password_bytes, bcrypt.gensalt())
hashed_str = hashed.decode('ascii')
# store out hashed_str for user
Validate:
# retrieve hashed_str for user from database
# password entered by user
password_bytes = password.encode('utf-8')
if len(password_bytes) > 72:
password_bytes = base64.b64encode(hashlib.sha256(password_bytes).digest())
valid = bcrypt.checkpw(password_bytes, hashed_str.encode('ascii'))