Python-Python3 生成 Google Authenticator 的 6 位验证码

代码如下:

复制代码
# -*- coding: utf-8 -*-

import hmac
import math
import base64
import struct
import hashlib
import time

def cal_google_code(secret_key):
    # secret key 的长度必须是 8 的倍数。所以如果 secret key 不符合要求,需要在后面补上相应个数的 "="
    secret_key_len = len(secret_key)
    secret_key_pad_len = math.ceil(secret_key_len / 8) * 8 - secret_key_len
    secret_key = secret_key + "=" * secret_key_pad_len

    duration_input = int(time.time()) // 30
    key = base64.b32decode(secret_key)
    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)

    # 生成的验证码未必是 6 位,注意要在前面补 0
    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

print(cal_google_code('your secret key'))
复制代码

 

【完】

posted on   John_ABC  阅读(1046)  评论(0编辑  收藏  举报

编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2018-05-24 Linux-task_struct和文件系统及管道的关系
2018-05-24 Linux-进程描述符 task_struct 详解

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示