zoukankan      html  css  js  c++  java
  • Python使用otp实现二步验证

    https://www.cnblogs.com/lori/p/11077161.html

    https://blog.coding.net/blog/two-factor-authentication

    https://www.cnblogs.com/voipman/p/6216328.html

    https://pyotp.readthedocs.io/en/latest/

    https://www.zhihu.com/question/20462696

    一、概述

    双因子认证(Two-factor authentication,也叫2FA),是一种通过组合两种不同的验证方式进行用户身份验证的机制。Google在2011年3月份,宣布在线上使用双因子认证,MSN和Yahoo紧随其后。

    双因子认证,除了需要验证用户名密码外,还要结合另外一种实物设备,如Rsa令牌,或者手机。
    双因子认证的产品大致可以分成两类:

    可以产生token的硬件设备
    智能手机的app

    手机短信验证码,登录微信公众号时的扫码确认都可以称为双因子认证。本文只介绍OTP一次性密码,也经常被称为token。

    二、相关术语

    OTP 是 One-Time Password的简写,表示一次性密码。分为以下两种

    HOTP 是HMAC-based One-Time Password的简写,表示基于HMAC算法加密的一次性密码。

      HOTP 是事件同步,通过某一特定的事件次序及相同的种子值作为输入,通过HASH算法运算出一致的密码。RFC4226。

    TOTP 是Time-based One-Time Password的简写,表示基于时间戳算法的一次性密码。

      TOTP 是时间同步,基于客户端的动态口令和动态口令验证服务器的时间比对,一般每60秒产生一个新口令,要求客户端和服务器能够十分精确的保持正确的时钟,客户端和服务端基于时间计算的动态口令才能一致。 RFC6238。 

    三、OTP实现原理


    通过上图我们已经看到输入算法的主要有两个元素,一个是共享密钥(也被称作种子),另外一个是计数(或者时间因子),经过特定的算法计算出结果。如果这两个元素全都一致,服务器端和客户端会计算出相同的结果,从而实现认证功能。

    四、使用Python实现OTP功能

    目前Python上有以下两大模块比较流行,我们以第一个pyotp为例介绍比较常用的TOTP。
    https://github.com/pyauth/pyotp
    https://github.com/tadeck/onetimepass/

    pyotp就是一个python模块,可以直接使用pip安装。

    [root@ipcpu-apollo ~]# python
    Python 3.6.5 (default, Jul 18 2018, 16:07:41) 
    [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 
    >>> import base64
    >>> string='this is s string'
    >>> secretKey = base64.b32encode(string.encode(encoding="utf-8"))
    >>> print(secretKey)
    b'ORUGS4ZANFZSA4ZAON2HE2LOM4======'
    >>> import pyotp
    >>> totp = pyotp.TOTP(secretKey)
    >>> totp.now()
    '863055'
    >>> totp.verify(863055)
    True

    五、pyotp和Google Authenticator的兼容

    pyotp一个比较大的亮点就是内置了和Google Authenticator的兼容,如下就可以产生Google Authenticator可以识别的字符串

    >>> pyotp.totp.TOTP('JBSWY3DPEHPK3PXP').provisioning_uri("alice@google.com", issuer_name="Secure App")
    'otpauth://totp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App'

    把这一串字符生成QR二维码,然后用Google Authenticator扫描就可以用。
    服务器端可以用如下方式验证

    >>> import pyotp
    >>> totp = pyotp.TOTP("JBSWY3DPEHPK3PXP")
    >>> print("Current OTP:", totp.now())
    Current OTP: 267343

    我们总结下,Google Authenticator实际上只存储了共享密钥,并通过共享密钥来产生OTP密码,其他的邮箱、签发人什么的都是为了标示共享密钥用来区分的。

  • 相关阅读:
    168. Excel Sheet Column Title
    171. Excel Sheet Column Number
    264. Ugly Number II java solutions
    152. Maximum Product Subarray java solutions
    309. Best Time to Buy and Sell Stock with Cooldown java solutions
    120. Triangle java solutions
    300. Longest Increasing Subsequence java solutions
    63. Unique Paths II java solutions
    221. Maximal Square java solutions
    279. Perfect Squares java solutions
  • 原文地址:https://www.cnblogs.com/sdadx/p/8137060.html
Copyright © 2011-2022 走看看