python使用scrypt加密和解密

作者:admin 发布日期:2024年8月15日 10:17 浏览量:41
    password = data['password']
    # 生成盐
    salt = os.urandom(16)
    # 使用 scrypt 哈希密码
    hashed_password = scrypt.hash(password.encode(), salt=salt)
    # 将哈希值和盐编码为 Base64 字符串以便于存储
    hashed_password_base64 = base64.b64encode(hashed_password).decode('utf-8')
    salt_base64 = base64.b64encode(salt).decode('utf-8')
    print("base64编码:", hashed_password_base64)
    print("base64编码:", salt_base64)

    # 将 Base64 编码的盐和哈希值解码回二进制
    stored_salt = base64.b64decode(salt_base64)
    stored_hashed_password = base64.b64decode(hashed_password_base64)
    print("stored_salt:", stored_salt)
    print("stored_hashed_password:", stored_hashed_password)
    # 使用相同的 scrypt 参数重新生成哈希值并验证密码
    is_correct = scrypt.hash(password, salt="stored_salt") == stored_hashed_password
    print("是否正确", is_correct)  # 输出: True 如果密码正确,否则 False