Skip to content

Latest commit

 

History

History
118 lines (70 loc) · 2.47 KB

File metadata and controls

118 lines (70 loc) · 2.47 KB
description:Detail guide on how to use TOTP and HOTP.

User Guide

.. rst-class:: lead

    Here are the detail guide on how to use TOTP and HOTP.


Use TOTP

TOTP is a Time-Based One-Time Password Algorithm defined in RFC6238.

import time
from otpauth import TOTP

totp = TOTP(b"user-secret")

# generate a code for now
code: int = totp.generate()

totp.verify(code)  # True

time.sleep(31)
totp.verify(code)  # False

Most of the time, you DO NOT NEED TO change the default configuration, but if you want, here is how:

totp = TOTP(b"user-secret", digit=8, algorithm="SHA256")

Use HOTP

HOTP is a An HMAC-Based One-Time Password Algorithm defined in RFC4226.

from otpauth import HOTP

htop = HOTP(b"user-secret")

# generate a code for now
code: int = htop.generate(4)

htop.verify(code, 4)  # True
htop.verify(code, 6)  # False

Tip

TOTP is based on HOTP, most of the time you would use TOTP.

Use base32 Secret

When the secret you have is a base32 encoded string, you don't have to decode it yourself. Instead, you can create the :class:`TOTP` and :class:`HTOP` instance with:

totp = TOTP.from_b32encode("OB4XI2DPNY")
hotp = HOTP.from_b32encode("OB4XI2DPNY")

It works well with and without the padding =. e.g.:

totp = TOTP.from_b32encode("OB4XI2DPNY======")
hotp = HOTP.from_b32encode("OB4XI2DPNY======")

This method also accepts secret in bytes.

Add to Authenticator App

There is a method .to_uri to generate the URI that most authenticator apps support. The Key URI Format looks like:

otpauth://TYPE/LABEL?PARAMETERS

An example of :meth:`TOTP.to_uri`:

>>> totp = TOTP.from_b32encode("OB4XI2DPNY")
>>> totp.to_uri("Typlog:lepture.com", "Authlib")
"otpauth://totp/Typlog:lepture.com?secret=OB4XI2DPNY&issuer=Authlib&algorithm=SHA1&digits=6&period=30"

Here shows the QR code of this URI:

_static/example-qr.png

You can test with an authenticator app.