基础概念
身份验证器
Authenticator
密码就算是身份验证器。
加密密钥,比如 SSH 的公钥私钥(密钥对)
动态密码
One-time Password, 缩写: OTP, 又叫做一次性密码
我们常用的的短信验证码就是一种非常方便快捷的动态密码形式。
早些年一些网络服务,比如谷歌、网易通行证等,可能会提供一个动态口令表,包含十几个密码,可以保存为图片,或者纯文本,上面的密码可以逐个使用,每个密码只能用一次。
- RFC4226 HOTP: An HMAC-Based One-Time Password Algorithm
- RFC6238 TOTP: Time-Based One-Time Password Algorithm
多重要素验证
Multi-factor authentication, 缩写: MFA
谷歌身份验证器
Google 身份验证器是一款 TOTP 与 HOTP 的两步验证软件令牌,此软件用于 Google 的认证服务。此项服务所使用的算法已列于 RFC 6238 和 RFC 4226 中。
Google 身份验证器给予用户一个六位到八位的一次性密码用于进行登录 Google 或其他站点时的附加验证。其同样可以给第三方应用生成口令,例如密码管理员或网络硬盘。先前版本的 Google 身份验证器开放源代码,但之后的版本以专有软件的形式公开。
虽然不是很大的创新,但基于谷歌的强大影响力,这个软件验证器被很多系统采用。
Just4Fun
import base64
import hashlib
import hmac
import struct
import time
def get_hotp_token(secret, intervals_no):
key = base64.b32decode(secret, True)
msg = struct.pack(">Q", intervals_no)
h = hmac.new(key, msg, hashlib.sha1).digest()
o = h[19] & 15
h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
return h
def get_totp_token(secret):
return get_hotp_token(secret, intervals_no=int(time.time()) // 30)
secret = 'MZXW633PN5XW6MZX'
for i in range(10):
print('%2d. %06d' % (i + 1, get_hotp_token(secret, intervals_no=i)))
for i in range(10):
print('%2d. %06d' % (i + 1, get_totp_token(secret)))
time.sleep(10)
参考资料与拓展阅读
- https://en.wikipedia.org/wiki/Authenticator
- https://en.wikipedia.org/wiki/One-time_password 一次性密码
- https://en.wikipedia.org/wiki/Multi-factor_authentication 多重要素验证
- https://en.wikipedia.org/wiki/Google_Authenticator
- https://github.com/tadeck/onetimepass/blob/master/onetimepass/__init__.py
- https://stackoverflow.com/questions/8529265/google-authenticator-implementation-in-python