Avatar CS Knowledge Wiki

One-Time Passwords (OTP) - Example

原文链接:https://www.yuque.com/yangguangfanxing/zuyi8o/gv42g2465yq53xl6

原文链接:https://www.yuque.com/yangguangfanxing/zuyi8o/gv42g2465yq53xl6 ↗

In this section, we shall provide an example of how to generate and validate One-Time Passwords (OTP) in Python. The Python library of our choice is PyOTP ↗, which implement the RFC 4226 ↗ and RFC 6238 ↗ standards. If you want to use this library you should follow the requirements in those standards. Installation:

pip install pyotp
bash

Server-Side Setup#

We need to create a base32 secret which has to be shared between the authentication server and the client. We will use Google Authenticator OpenSource ↗ OTP model which produce a URI for an exchange, the secret and additional client-server details. It includes the shared secret, the client’s username, and the issuer’s name.

import pyotp

base32secret = pyotp.random_base32()
print('Secret:', base32secret)

totp_uri = pyotp.totp.TOTP(base32secret).provisioning_uri(
    "alice@google.com",
    issuer_name="Secure App")
print(totp_uri)
python

Run the above code example: https://repl.it/@nakov/OTP-Server-Side-in-Python ↗.

Sample output:

Secret: S3K3TPI5MYA2M67V
otpauth://totp/Secure%20App:alice%40google.com?secret=S3K3TPI5MYA2M67V&issuer=Secure%20App
bash

Client-Side Setup#

Once the client stores the secret in a secure way, in a time-interval of a 30 seconds (by default) a new code will be generated.

import pyotp
import time

base32secret = 'S3K3TPI5MYA2M67V' # 这里就是上面Server输出的shared secret
print('Secret:', base32secret)

totp = pyotp.TOTP(base32secret)
print('OTP code:', totp.now())
time.sleep(30)
print('OTP code:', totp.now())
python

Run the above code example: https://repl.it/@nakov/OTP-Client-Side-in-Python ↗.

Sample output:

Secret: S3K3TPI5MYA2M67V
OTP code: 339838
OTP code: 284911
bash

Working Example#

You can install Google Authenticator from Google Play ↗ or App Store ↗ and scan the QR code below:

Example validation check:

import pyotp

base32secret = 'S3K3TPI5MYA2M67V'
print('Secret:', base32secret)

totp = pyotp.TOTP(base32secret)
your_code = '123456'
print(totp.verify('Code Valid:', your_code))
python

Run the above code example: https://repl.it/@nakov/QR-code-scanner-in-Python ↗.

Output:

Secret: S3K3TPI5MYA2M67V
Code Valid: True
bash
Knowledge map

知识图谱

当前文档、同目录指南与引用关系。

准备中 全局图谱

正在构建知识图谱...

拖动节点 · 滚动缩放 · 点击打开

帮助与支持

这篇文档有帮助吗?

请给我们反馈以改进文档质量
(点击按钮后会打开邮箱)

帮助改进文档

所有文档均开源,发现问题或不清楚的地方?提交 PR 来帮助改进。

编辑此页面 了解如何贡献 →

需要更多帮助?

加入社区或直接联系获取支持

文件管理器 /
位置 /
内容
Knowledge explorer

知识图谱

全部知识 准备图谱...
文章 文档 标签 分类

正在加载知识网络...

拖动节点 · 滚动缩放 · 单击查看详情 · 双击打开页面
标签云 / Tag Cloud