TOTPSecret()

edit

Generates a random shared secret for two-factor authentication (2FA).

Returns a Base32-encoded string that can be shared with authenticator apps like Google Authenticator via a QR code.

Requires Extension: Crypto Extension

TOTPSecret( length=numeric );

Returns: String

Argument Description Default
length
numeric, optional
edit

Secret length in bytes (16-128). Default 20 bytes (160-bit) for SHA1. Use 32 for SHA256 or 64 for SHA512.

20

Usage Notes

edit

Store the secret securely in your database — it's equivalent to a password. Only show it to the user once during 2FA setup (typically as a QR code via TOTPGenerateUri()).

The default 20-byte secret is sufficient for most applications. Google Authenticator and most other apps work with 20-byte secrets.

Examples

edit
// Generate a random TOTP secret for two-factor authentication (2FA)
// Returns a Base32-encoded string suitable for use with authenticator apps
secret = TOTPSecret();
// e.g. "JBSWY3DPEHPK3PXP4GWRGZLQ..."  (32 characters = 20 bytes)

// Each call generates a unique secret - store this securely per user secret1 = TOTPSecret(); secret2 = TOTPSecret(); // secret1 != secret2
// Custom length (in bytes, range 16-128). Default is 20 bytes. // Longer secrets provide more security but most authenticator apps work fine with 20 secret = TOTPSecret( 32 ); // 32 bytes = 256 bits

See also