Generate a TOTP Secret Key
Generate a cryptographically secure TOTP secret key for two-factor authentication. Learn about Base32 encoding, key length requirements, and best practices for secret storage.
Detailed Explanation
Generating a Secure TOTP Secret
The TOTP secret key is the foundation of the entire authentication process. It is a randomly generated byte sequence that must be shared securely between the server and the user's authenticator app — and never exposed again after the initial setup.
Key Length Recommendations
RFC 4226 (the HOTP specification that TOTP builds on) recommends a minimum secret length of 160 bits (20 bytes) for HMAC-SHA1. For stronger hash algorithms:
- SHA-1: 20 bytes minimum (160 bits)
- SHA-256: 32 bytes recommended (256 bits)
- SHA-512: 64 bytes recommended (512 bits)
Most implementations, including Google Authenticator, default to 20-byte secrets with SHA-1.
Generating the Secret
The secret must be generated using a cryptographically secure random number generator (CSPRNG). In different environments:
// Browser (Web Crypto API)
const bytes = new Uint8Array(20);
crypto.getRandomValues(bytes);
// Node.js
const crypto = require('crypto');
const bytes = crypto.randomBytes(20);
// Python
import secrets
secret_bytes = secrets.token_bytes(20)
Base32 Encoding
TOTP secrets are encoded in Base32 (RFC 4648) for human readability and compatibility with authenticator apps. Base32 uses the characters A-Z and 2-7, which avoids ambiguous characters like 0/O and 1/I.
A 20-byte secret becomes a 32-character Base32 string:
Raw bytes: 48 65 6c 6c 6f ...
Base32: JBSWY3DPEHPK3PXP...
Storage Best Practices
- Encrypt at rest: never store plaintext secrets in your database
- Use a dedicated secrets manager or encrypted column
- Show the secret only once during enrollment
- Generate unique secrets per user — never reuse secrets
- Provide backup codes alongside the TOTP secret for account recovery
Use Case
Generating TOTP secrets is the first step when enabling two-factor authentication for user accounts. Backend developers need to create secrets during the enrollment flow, encode them in Base32, embed them in a QR code URI, and store them securely. This guide covers the complete process from random byte generation through to safe storage, which is critical for any application adding TOTP-based 2FA.