Go OTP TOTP HOTP
Contents
Go OTP TOTP HOTPgogolangotpsecurity
More and more systems add multi-factor authentication for security. OTP is one of the relatively simple and convenient MFA schemes. This post briefly covers the concepts and gives totp and hotp examples based on go1.19.2. For more, see kit4go/otp.
Copyright notice: This is an original article by xwi88, licensed under CC BY-NC 4.0. Commercial use is prohibited; please cite the source when reposting. Follow at https://github.com/xwi88
Concepts
- OTP: One-Time Password.
- A single-use password
- TOTP: Time-based One-time Password Algorithm (RFC 6238): time-based OTP, the most commonly used method.
- A one-time password generated from a timestamp algorithm
- Generated from a secret key and the current time
- Usually produces a new code every 30 or 60 seconds
- Requires the client and server to keep fairly accurate clocks
- HOTP: HMAC-based One-time Password Algorithm (RFC 4226): counter-based OTP, which TOTP builds upon.
- A one-time password generated from the
HMACalgorithm
- A one-time password generated from the
Use cases
- Server login dynamic-password verification (cloud servers, enterprise platforms, etc.)
- github, twitter, google login two-factor authentication
- Corporate intranet proxy login 2FA
- Bank transfer dynamic passwords
- Hardware tokens for online banking and online games
- 2FA / MFA and the like
Products
- Microsoft Authenticator: microsoft-authenticator
- Cross-app, simple, fast and highly secure 2FA
- Recommended for personal use ☆☆☆☆☆
- Google Authenticator: google-authenticator
- Bank token: bound to a specific account/card only
- Vendor-specific OTP security apps: limited to that vendor’s products
Principle
OTP(K, C) = Truncate(HMAC-SHA-1(K, C))
K: secret key stringC: a numberHMAC-SHA-1: HMAC using SHA-1Truncate: truncates the encrypted string
For HMAC-SHA-1 encryption, Truncate works as follows:
- HMAC-SHA-1 produces a 20-byte secret string
- Take the last byte of those 20 bytes, and use its low 4 bits as the index offset into the encrypted string
- Starting at that offset, take 4 bytes and combine them into an integer (big-endian)
- Take the last 6 or 8 digits of that integer and return them as a string
OTP
C: a number representing a random value- Other parameters as defined above
TOTP
C: a random value derived from a timestampC = (T - T0) / T1- T: the current timestamp
- T0: the epoch start, usually 0
- T1: the time step, customized per your needs
- Usually 30, meaning the generated code is valid for
30s
- Usually 30, meaning the generated code is valid for
- Other parameters as defined above
- The hash function is usually
SHA2, i.e. event-synchronous verification based on aSHA-256orSHA-512hash
HOTP
C: a number representing a random value- Other parameters as defined above
Implementations
Usage
go get -u github.com/v8fg/kit4go
| |
More examples are in the source
otp/*_test.gofiles