什麼是密碼雜湊?
密碼雜湊 (Password Hashing) 是指將明文密碼轉換為不可逆的雜湊值,確保即使資料庫外洩,攻擊者也無法還原原始密碼。通常應用於使用者註冊時的密碼儲存,以及登入時的密碼驗證流程。
密碼雜湊基礎語法
- 安裝依賴套件:使用
pip install "passlib[argon2]"安裝 FastAPI 的 argon2 演算法 - 初始化雜湊:建立 CryptContext 物件並指定
schemes=["argon2"],設定deprecated="auto"以自動處理舊版雜湊 - 執行雜湊 (Hash):呼叫
.hash(password)方法,將使用者輸入的明文密碼轉為雜湊值 - 驗證密碼 (Verify):呼叫
.verify(plain_password, hashed_password)方法,比對輸入的明文與資料庫中的雜湊值是否匹配
# 必須先安裝套件:pip install "passlib[argon2]"
from passlib.context import CryptContext # 匯入密碼處理上下文類別
# 設定密碼雜湊情境 (Context)
pwd_context = CryptContext(schemes=["argon2"], deprecated="auto")
def get_password_hash(password: str) -> str:
"""
將明文密碼轉換為雜湊值
"""
return pwd_context.hash(password) # 執行雜湊運算並回傳結果字串
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""
驗證明文密碼與雜湊值是否匹配
"""
# 注意參數順序:先傳入明文 (plain),再傳入雜湊 (hashed)
return pwd_context.verify(plain_password, hashed_password)
if __name__ == "__main__":
# 模擬使用者註冊:輸入明文密碼
user_input_raw = "my_super_secret_123" # 使用者輸入的原始密碼
# 存入資料庫前進行雜湊處理
db_stored_hash = get_password_hash(user_input_raw) # 取得雜湊後的字串
print(f"明文密碼: {user_input_raw}") # 印出明文 (僅供教學示範)
print(f"資料庫儲存的雜湊值: {db_stored_hash}") # 印出類似 $argon2id$... 的雜湊值
# 模擬使用者登入:輸入正確密碼
login_attempt = "my_super_secret_123" # 再次輸入相同密碼
is_valid = verify_password(login_attempt, db_stored_hash) # 比對密碼
print(f"登入驗證結果 (正確密碼): {is_valid}") # 預期輸出 True
# 模擬使用者登入:輸入錯誤密碼
wrong_attempt = "wrong_password" # 輸入不同密碼
is_valid_wrong = verify_password(wrong_attempt, db_stored_hash) # 比對密碼
print(f"登入驗證結果 (錯誤密碼): {is_valid_wrong}") # 預期輸出 False
















