Time-based (TOTP) and HMAC-based (HOTP) One-Time Password library
- Quick Start
This library is also compatible with Google Authenticator, and includes additional methods to allow you to work with Google Authenticator.
- Typescript support
- Class interfaces
- Function interfaces
- Async interfaces
- Pluggable modules (crypto / base32)
- Presets provided
default-async (same as default, but with async methods)
v11 (adapter for previous version)
npm install otplib --save
;const secret = 'KVKFKRCPNZQUYMLXOVYDSQKJKZDTSRLD';// Alternative:// const secret = authenticator.generateSecret();// Note: .generateSecret() is only available for authenticator and not totp/hotpconst token = authenticator;tryconst isValid = authenticator;// orconst isValid = authenticator;catch err// Possible errors// - options validation// - "Invalid input - it is not base32 encoded string" (if thiry-two is used)console;
Please replace "authenticator" with "totp" or "hotp" depending on your requirements.
// For TOTP;const token = totp;const isValid = totp;const isValid = totp;// For HOTP;const token = hotp;const isValid = hotp;const isValid = hotp;
For all available APIs, please refer to API Documentation.
The browser preset is a self-contained
umd module, and it is provided in a separate bundle.
npm install @otplib/preset-browser --save
The following is an example, where we are using the scripts hosted by
For more details, please refer to the @otplib/preset-browser documentation.
API / Demo Website
|v12.x||Website / API / Readme|
|v11.x||API / Readme|
|v10.x and below||Available via git history|
This library follows
semver. As such, major version bumps usually mean API changes or behavior changes.
Please check upgrade notes for more information,
especially before making any major upgrades.
To simplify releases, all packages within this repository have their versions synced. Therefore, if there are any releases or updates to a package, we will bump all packages.
Check out the release notes associated with each tagged versions in the releases page.
|Release Type||Version Pattern||Command|
|Current / Stable||0.0.0||
Migrating from v11.x
v12.x is a huge architectural and language rewrite. Please check out the docs if you are migrating. A preset adapter is available to provide methods that behave like
// Update; // v11.x// to;// There should be no changes to your current code.// However, deprecated or modified class methods will have console.warn.
All instantiated classes will have their options inherited from their respective options
generator. i.e. HOTP from
hotpOptions, TOTP from
and Authenticator from
All OTP classes have an object setter and getter method to override these default options.
;// settingauthenticatoroptions = digits: 6 ;totpoptions = digits: 6 ;hotpoptions = digits: 6 ;// gettingconst opts = authenticatoroptions;const opts = totpoptions;const opts = hotpoptions;// reset to defaultauthenticator;totp;hotp;// getting all options, with validation// and backfilled with library defaultsconst opts = authenticator;const opts = totp;const opts = hotp;
|algorithm||string||The algorithm used for calculating the HMAC.|
|createDigest||function||Creates the digest which token is derived from.|
|createHmacKey||function||Formats the secret into a HMAC key, applying transformations (like padding) where needed.|
|digest||string||USE WITH CAUTION. Same digest = same token.
Used in cases where digest is generated externally. (eg: async use cases)
|digits||integer||The length of the token.|
|encoding||string||The encoding that was used on the secret.|
// HOTP defaultsalgorithm: 'sha1'createDigest: undefined // to be provided via a @otplib/plugin-*createHmacKey: hotpCreateHmacKeydigits: 6encoding: 'ascii'
Note: Includes all HOTP Options
|epoch||integer||USE WITH CAUTION. Same epoch = same token.
Starting time since the UNIX epoch (seconds).
|step||integer||Time step (seconds)|
|Tokens in the previous and future x-windows that should be considered valid.
If integer, same value will be used for both.
Alternatively, define array:
// TOTP defaults// ...includes all HOTP defaultscreateHmacKey: totpCreateHmacKeyepoch: Datestep: 30window: 0
Note: Includes all HOTP + TOTP Options
|createRandomBytes||function||Creates a random string containing the defined number of bytes to be used in generating a secret key.|
|keyEncoder||function||Encodes a secret key into a Base32 string before it is sent to the user (in QR Code etc).|
|keyDecoder||function||Decodes the Base32 string given by the user into a secret.|
// Authenticator defaults// ...includes all HOTP + TOTP defaultsencoding: 'hex'createRandomBytes: undefined // to be provided via a @otplib/plugin-*keyEncoder: undefined // to be provided via a @otplib/plugin-*keyDecoder: undefined // to be provided via a @otplib/plugin-*
TypeScript support was introduced in
v10.0.0, which added type definitions over
v12.0.0, the library has been re-written in Typescript from the ground up.
async support was introduced in
v12.0.0 as an additional core library.
You to find more details in the core-async folder.
@otplib/preset-browser is a
umd bundle with some node modules replaced to reduce the browser size.
The approximate size for the optimised, minified + gzipped bundle is 9.53KB.
Paired with the gzipped browser
buffer.js module, it would be about
7.65KB + 9.53KB = 17.18KB.
For more details, please refer to the @otplib/preset-browser documentation.
Length of Secrets
In RFC 6238, the secret / seed length for different algorithms are predefined:
HMAC-SHA1 - 20 bytesHMAC-SHA256 - 32 bytesHMAC-SHA512 - 64 bytes
As such, the length of the secret provided (after any decoding) will be padded and sliced according to the expected length for respective algorithms.
Difference between Authenticator and TOTP
The default encoding option has been set to
hex (Authenticator) instead of
Google Authenticator requires keys to be base32 encoded. It also requires the base32 encoder to be RFC 3548 compliant.
OTP calculation will still work should you want to use other base32 encoding methods (like Crockford's Base32) but it will NOT be compatible with Google Authenticator.
const secret = authenticator; // base32 encoded hex secret keyconst token = authenticator;
Displaying a QR code
You may want to generate and display a QR Code so that users can scan
instead of manually entering the secret. Google Authenticator and similar apps
take in a QR code that holds a URL with the protocol
which you get from
Google Authenticator will ignore the
See the keyuri documentation
for more information.
If you are using a different authenticator app, check the documentation for that app to see if any options are ignored, which will result in invalid tokens.
While this library provides the "otpauth" uri, you'll need a library to generate the QR Code image.
An example is shown below:
// npm install qrcode;;const user = 'A user name, possibly an email';const service = 'A service name';// v11.x and aboveconst otpauth = authenticator;// v10.x and belowconst otpauth = authenticator;qrcode;
Note: For versions
keyuridoes not URI encode
service. You'll need to do so before passing in the parameteres.
Getting Time Remaining / Time Used
Helper methods for getting the remaining time and used time within a validity period
authenticator token were introduced in
authenticator; // or totp.timeUsed();authenticator; // or totp.timeRemaining();// The start of a new token would be when:// - timeUsed() === 0// - timeRemaining() === step
Using with Expo
Expo contains modified crypto implmentations targeted at the platform.
otplib does not provide an
expo specified package, with the re-architecture
otplib, you can now provide an expo native
createDigest to the library.
Alternatively, you can make use of crypto provided by
the bundled browser umd module
Pull Requests are much welcomed for a native expo implementation as well.
Exploring with local-repl
If you'll like to explore the library with
local-repl you can do so as well.
# after cloning the repo:npm run setupnpm run buildnpx local-repl# You should see something like:# Node v8.9.4, local-repl 4.0.0# otplib 10.0.0# Context: otplib# [otplib] >[otplib] > secret = 'KVKFKRCPNZQUYMLXOVYDSQKJKZDTSRLD'[otplib] > otplib.authenticator.generate
OTP Backup Codes
It is common for services to also provide a set of backup codes to authenticate and bypass the OTP step in the event that you are not able to access your 2FA device or have misplaced the device.
As this process is separate from the specifications for OTP, this library does not provide any backup code related verification logic, and thus would have to be implemented separately.
Thanks goes to these wonderful people (emoji key):
💻 📖 🚧 ⚠️
Ahmed Hamdy (@shakram02)
This project follows the all-contributors specification. Contributions of any kind welcome!
otplib is MIT licensed