Skip to content

otplib API Documentation / @otplib/core / generateSecret

Function: generateSecret()

generateSecret(options): string

Defined in: packages/core/src/utils.ts:663

Generate a random Base32-encoded secret

Creates a cryptographically secure random secret suitable for OTP generation. The default length of 20 bytes (160 bits) matches RFC 4226 recommendations and provides good security margin.

Parameters

options

SecretOptions

Secret generation options

Returns

string

Base32-encoded secret string (without padding for Google Authenticator compatibility)

Examples

ts
import { generateSecret } from '@otplib/core';
import { NodeCryptoPlugin } from '@otplib/plugin-crypto-node';
import { ScureBase32Plugin } from '@otplib/plugin-base32-scure';

const secret = generateSecret({
  crypto: new NodeCryptoPlugin(),
  base32: new ScureBase32Plugin(),
});
// Returns: 'JBSWY3DPEHPK3PXP...' (32 characters)
ts
const secret = generateSecret({
  crypto: new NodeCryptoPlugin(),
  base32: new ScureBase32Plugin(),
  length: 32, // 256 bits for SHA-256
});

Released under the MIT License.