1. 程式人生 > >time-based基於google key生成6位驗證碼(google authenticator)

time-based基於google key生成6位驗證碼(google authenticator)

input div 如果 multipl turn 啟用 struct highlight time

由於公司服務器啟用了雙因子認證,登錄時需要再次輸入谷歌身份驗證器生成的驗證碼。而生成驗證碼是基於一套固定的算法的,以當前時間為基礎,基於每個人的google key去生成一個6位的驗證碼

以下為python3實現

import hmac
import base64
import struct
import hashlib
import time


def cal_google_code(secret_key):
    duration_input = int(time.time())//30
    key = base64.b32decode(secret_key)  # Length of the key must be a multiplier of eight
    msg = struct.pack(">Q", duration_input)
    google_code = hmac.new(key, msg, hashlib.sha1).digest()
    o = google_code[19] & 15
    google_code = str((struct.unpack(">I", google_code[o:o+4])[0] & 0x7fffffff) % 1000000)
    if len(google_code) == 5:  # Only if length of the code is 5, a zero will be added at the beginning of the code.
        google_code = ‘0‘ + google_code
    return google_code

首先算法對google key的長度是有要求的。key的長度必須是8的倍數,所以如果運維給的key不符合要求,需要在後面補上相應個數的"="。

按照此算法,生成的驗證碼未必是6位,需要在前面補0。

time-based基於google key生成6位驗證碼(google authenticator)