Two-Factor Auth Guide
TOTP vs HOTP
| Feature | TOTP | HOTP |
|---|---|---|
| Standard | RFC 6238 | RFC 4226 |
| Basis | Time (30s window) | Counter |
| Use Case | Google Auth, Authy | Hardware tokens |
| Expiry | 30s | Until used |
Implementation Examples
npm install otplib
const { authenticator } = require('otplib');
// Generate secret
const secret = authenticator.generateSecret();
console.log('Secret:', secret);
// Generate OTP URL for QR code
const otpauth = authenticator.keyuri('[email protected]', 'MyApp', secret);
// Verify token
const token = authenticator.generate(secret);
const isValid = authenticator.verify({ token, secret });
pip install pyotp qrcode
import pyotp, qrcode
# Generate secret
secret = pyotp.random_base32()
# TOTP
totp = pyotp.TOTP(secret)
print(totp.now()) # Current code
print(totp.verify('123456')) # Verify
# QR code URL
uri = totp.provisioning_uri("[email protected]", issuer_name="MyApp")
go get github.com/pquerna/otp/totp
import "github.com/pquerna/otp/totp"
// Generate key
key, _ := totp.Generate(totp.GenerateOpts{
Issuer: "MyApp",
AccountName: "[email protected]",
})
// Validate code
valid := totp.Validate(code, key.Secret())
QR Code otpauth:// Format
otpauth://totp/LABEL?secret=SECRET&issuer=ISSUER&algorithm=SHA1&digits=6&period=30
| Parameter | Description |
|---|---|
| secret | Base32 encoded shared secret |
| algorithm | SHA1 (default), SHA256, SHA512 |
| digits | 6 or 8 |
| period | 30s (default) |