1. 程式人生 > >Python計算谷歌身份驗證器(google authenticator)的驗證碼

Python計算谷歌身份驗證器(google authenticator)的驗證碼

谷歌身份驗證碼是繼續時間計算的。服務端和客戶端各自根據金鑰,基於時間為30秒為驗證碼,網上搜了很多,一直報錯,還是看我同事何澤

解決報錯TypeError: Incorrect padding 的問題,因為祕鑰不是8的倍數,需要用“=”補足,不知道為啥網上資料這麼難搜尋

import hmac, base64, struct, hashlib, time

def calGoogleCode(secretKey):
    input = int(time.time())//30
lens = len(secretKey)
    lenx = 8 - (lens % 4 if lens % 4 else 
4) secretKey += lenx * '=' print secretKey, ' ----- ' ,lenx , lens ,'|' key = base64.b32decode(secretKey) msg = struct.pack(">Q", input) googleCode = hmac.new(key, msg, hashlib.sha1).digest() o = ord(googleCode[19]) & 15 googleCode = str((struct.unpack(">I", googleCode[o:o+4
])[0] & 0x7fffffff) % 1000000) if len(googleCode) == 5: googleCode = '0' + googleCode return googleCode