Overview

當使用者在表單中提交了敏感資訊,例如密碼時,如果未經處理直接將密碼存入資料庫,密碼將以明碼的方式儲存。這樣的問題在於,如果資料庫不幸被有心人士訪問,所有用戶的密碼將被一覽無遺。

因此通常在儲存用戶密碼時會將密碼先透過 hash 加密後再儲存到資料庫,這樣做的好處是就算訪問了資料庫,也無法得知用戶所設定的原始密碼,只能得到處理過的加密資料,無法輕易反推回用戶的原始密碼。

Usage

werkzeug

此處使用 werkzeug 套件來加密與驗證用戶密碼。

from werkzeug.security import generate_password_hash, check_password_hash

pwd_1 = 'qwerasdfzxcv'
pwd_2 = 'zxcvasdfqwer'
print(pwd_1)
print(pwd_2)

pwd_hash_11 = generate_password_hash(pwd_1)
pwd_hash_12 = generate_password_hash(pwd_1)
pwd_hash_2 = generate_password_hash(pwd_2)
print(pwd_hash_11)
print(pwd_hash_12)
print(pwd_hash_2)

status_11 = check_password_hash(pwd_hash_11, pwd_1)
status_12 = check_password_hash(pwd_hash_11, pwd_1)
status_2 = check_password_hash(pwd_hash_11, pwd_2)
print('status_11: ', status_11)
print('status_12: ', status_12)
print('status_2: ', status_2)

class

from werkzeug.security import generate_password_hash, check_password_hash

class User:
    def __init__(self, username=None, password=None):
        self.username = username
        self.password = password

    @property
    def password(self):
        raise AttributeError('password is not readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

test = User('admin', 'test')
print(test.verify_password('test'))  # True
print(test.verify_password('1234'))  # False
print(test.username)  # admin
print(test.password_hash)  # pbkdf2:sha256......