python 實現google authenticator 認證
一、環境描述
windows開發環境 python:3.6 所需安裝包 pyotp qrcode Image
二、實現原理
1.使用pyotp 的python模塊生成google auth 需要的密鑰 2.根據密鑰生成條形碼圖片 3.使用google authenticator 客戶端掃描條形碼,客戶端根據時間及密鑰經過算法 生成6位數的驗證碼 4.平台二次認證通過對輸入的驗證碼進行校驗,校驗也是基於時間和密鑰
三、代碼實現
3.1隨機密鑰生成
a. 安裝模塊包
安裝模塊包 pyotp
pip install pyotp
b. 密鑰生成
import pyotp gtoken = pyotp.random_base32(64) #獲取隨機密鑰,存於用戶表中,隨機64位
3.2 圖片二維碼生成
a. 安裝模塊包
安裝模塊包
pip install qrcode
qrcode 依賴 Image 這個包:
pip install Image
b.根據用戶名及密鑰生成二維碼
按 Ctrl+C 復制代碼
按 Ctrl+C 復制代碼
c. 使用功能
result = get_qrcode(gtoken, 'supery') print('result', result) LWGOAZX5PQQLR34BOJRLVHHC4CRVFVXP3PGCYHWZ2PVKLRSJNCDWR6XPL4LAJRST filepath D:\dev\PYSCRIPTS\xxx\mfa\static\image\LWGOAZX5PQQLR34BOJRLVHHC4CRVFVXP3PGCYHWZ2PVKLRSJNCDWR6XPL4LAJRST.png result True
3.3 效驗驗證碼正確性
a. 下載好google authenticator客戶端
客戶掃描圖片,前端頁面驗證用戶名和密碼后,顯示對應的條形碼圖片 windows上打開圖片后掃描二維碼 D:\dev\PYSCRIPTS\xxx\mfa\static\image\LWGOAZX5PQQLR34BOJRLVHHC4CRVFVXP3PGCYHWZ2PVKLRSJNCDWR6XPL4LAJRST.png 實際生產環境通過頁面直接顯示該二維碼圖片,進行掃描
b. 效驗代碼
import pyotp def Google_Verify_Result(secret_key, verifycode): t = pyotp.TOTP(secret_key) result = t.verify(verifycode) # 對輸入驗證碼進行校驗,正確返回True msg = result if result is True else False return msg
c. 使用功能
secret_key = 'LWGOAZX5PQQLR34BOJRLVHHC4CRVFVXP3PGCYHWZ2PVKLRSJNCDWR6XPL4LAJRST' res = Google_Verify_Result(secret_key, 247724) print('res', res)
res False