otplib vs speakeasy vs authenticator
Two-Factor Authentication Libraries Comparison
1 Year
otplibspeakeasyauthenticatorSimilar Packages:
What's Two-Factor Authentication Libraries?

Two-factor authentication (2FA) libraries are essential tools in web development that provide mechanisms to enhance security by requiring two forms of verification before granting access to a user. These libraries simplify the implementation of 2FA, allowing developers to integrate time-based one-time passwords (TOTP) or other authentication methods into their applications. By leveraging these libraries, developers can protect user accounts from unauthorized access, significantly reducing the risk of security breaches and enhancing user trust.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
otplib580,8802,035-875 years agoMIT
speakeasy329,6272,720-649 years agoMIT
authenticator67,155---7 years ago(MIT or Apache-2.0)
Feature Comparison: otplib vs speakeasy vs authenticator

Algorithm Support

  • otplib:

    Otplib supports both TOTP and HOTP algorithms, offering flexibility for developers who may need to implement different types of one-time passwords. This dual support allows for a broader range of applications and use cases.

  • speakeasy:

    Speakeasy also supports both TOTP and HOTP algorithms, providing a robust solution for developers. Its API is designed to be intuitive, making it easy to implement either algorithm as needed.

  • authenticator:

    Authenticator primarily focuses on TOTP, providing a simple interface for generating and validating time-based one-time passwords. It is lightweight and easy to use, making it ideal for basic 2FA implementations.

Ease of Use

  • otplib:

    Otplib offers a more comprehensive set of features, which may introduce a slight learning curve. However, its well-documented API and examples make it accessible for developers who need advanced functionality.

  • speakeasy:

    Speakeasy strikes a balance between ease of use and functionality. Its API is straightforward, and it provides helpful utilities like QR code generation, making it user-friendly for developers looking to implement 2FA quickly.

  • authenticator:

    Authenticator is designed with simplicity in mind. Its API is minimalistic, allowing developers to quickly implement 2FA without extensive configuration or setup. This makes it an excellent choice for projects with tight deadlines.

Customization

  • otplib:

    Otplib is highly customizable, allowing developers to tweak various parameters such as the time step for TOTP generation and the hashing algorithm used. This flexibility makes it suitable for applications with specific security requirements.

  • speakeasy:

    Speakeasy provides several customization options, including the ability to set custom encoding and token lengths. This makes it adaptable to different application needs while maintaining a user-friendly interface.

  • authenticator:

    Authenticator offers limited customization options, focusing on core TOTP functionality. This is beneficial for developers who prefer a straightforward implementation without the need for extensive configuration.

QR Code Generation

  • otplib:

    Otplib does not provide QR code generation directly, but it can easily be integrated with other libraries to generate QR codes for user setup, allowing for a seamless user experience.

  • speakeasy:

    Speakeasy includes built-in support for generating QR codes, making it easy for users to set up their 2FA using mobile authenticator apps. This feature enhances usability and simplifies the onboarding process.

  • authenticator:

    Authenticator does not include built-in support for QR code generation, which may require additional libraries or manual implementation for user setup.

Community and Maintenance

  • otplib:

    Otplib has a larger community and is actively maintained, ensuring that developers have access to updates and support. Its popularity also means that there are numerous resources available for troubleshooting and implementation.

  • speakeasy:

    Speakeasy enjoys a robust community and is well-maintained, providing regular updates and enhancements. The active community contributes to a wealth of resources and documentation, making it easier for developers to find help and best practices.

  • authenticator:

    Authenticator has a smaller community and fewer contributors, which may impact the speed of updates and support. However, its simplicity means that it requires minimal maintenance.

How to Choose: otplib vs speakeasy vs authenticator
  • otplib:

    Opt for Otplib if you require a comprehensive library that supports both TOTP and HOTP (HMAC-based One-Time Password) algorithms. It is highly customizable and offers advanced features like token generation, validation, and various encoding options, making it suitable for more complex authentication needs.

  • speakeasy:

    Select Speakeasy if you are looking for a feature-rich library that provides a simple API for generating and verifying TOTP and HOTP tokens. It also includes support for QR code generation, making it easy to integrate with mobile authenticator apps, which enhances user experience.

  • authenticator:

    Choose Authenticator if you need a straightforward solution for generating and validating TOTP tokens, especially if you prefer a minimalistic approach with fewer dependencies. It is particularly useful for projects that require basic 2FA functionality without additional features.

README for otplib

otplib

Time-based (TOTP) and HMAC-based (HOTP) One-Time Password library

npm Build Status Coverage Status npm downloads TypeScript Support


About

otplib is a JavaScript One Time Password (OTP) library for OTP generation and verification.

It implements both HOTP - RFC 4226 and TOTP - RFC 6238, and are tested against the test vectors provided in their respective RFC specifications. These datasets can be found in the tests/data folder.

This library is also compatible with Google Authenticator, and includes additional methods to allow you to work with Google Authenticator.

Features

  • Typescript support
  • Class interfaces
  • Function interfaces
  • Async interfaces
  • Pluggable modules (crypto / base32)
    • crypto (node)
    • crypto-js
    • @ronomon/crypto-async
    • thirty-two
    • base32-encode + base32-decode
  • Presets provided
    • browser
    • default (node)
    • default-async (same as default, but with async methods)
    • v11 (adapter for previous version)

Quick Start

If you need to customise your base32 or crypto libraries, check out the In-Depth Guide and Available Packages

In Node.js

npm install otplib --save
import { authenticator } from 'otplib';

const secret = 'KVKFKRCPNZQUYMLXOVYDSQKJKZDTSRLD';
// Alternative:
// const secret = authenticator.generateSecret();
// Note: .generateSecret() is only available for authenticator and not totp/hotp

const token = authenticator.generate(secret);

try {
  const isValid = authenticator.check(token, secret);
  // or
  const isValid = authenticator.verify({ token, secret });
} catch (err) {
  // Possible errors
  // - options validation
  // - "Invalid input - it is not base32 encoded string" (if thiry-two is used)
  console.error(err);
}

Please replace "authenticator" with "totp" or "hotp" depending on your requirements.

// For TOTP
import { totp } from 'otplib';
const token = totp.generate(secret);
const isValid = totp.check(token, secret);
const isValid = totp.verify({ token, secret });

// For HOTP
import { hotp } from 'otplib';
const token = hotp.generate(secret, counter);
const isValid = hotp.check(token, secret, counter);
const isValid = hotp.verify({ token, secret, counter });

For all available APIs, please refer to API Documentation.

In Browser

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 unpkg.com.

<script src="https://unpkg.com/@otplib/preset-browser@^12.0.0/buffer.js"></script>
<script src="https://unpkg.com/@otplib/preset-browser@^12.0.0/index.js"></script>

<script type="text/javascript">
  // window.otplib.authenticator
  // window.otplib.hotp
  // window.otplib.totp
</script>

For more details, please refer to the @otplib/preset-browser documentation.

References

API / Demo Website

| Version | Links | | --------------- | ----------------------------------------------------------------------------------- | | v12.x | Website / API / Readme | | v11.x | API / Readme | | v10.x and below | Available via git history |

Versioning

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 | npm install otplib | npm | | Release Candidate | 0.0.0-0 | npm install otplib@next | npm |

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 v11.x of otplib.

// Update
import { authenticator } from 'otplib'; // v11.x
// to
import { authenticator } from '@otplib/preset-v11';

// There should be no changes to your current code.
// However, deprecated or modified class methods will have console.warn.

Available Options

All instantiated classes will have their options inherited from their respective options generator. i.e. HOTP from hotpOptions, TOTP from totpOptions and Authenticator from authenticatorOptions.

All OTP classes have an object setter and getter method to override these default options.

For example,

import { authenticator, totp, hotp } from 'otplib';

// setting
authenticator.options = { digits: 6 };
totp.options = { digits: 6 };
hotp.options = { digits: 6 };

// getting
const opts = authenticator.options;
const opts = totp.options;
const opts = hotp.options;

// reset to default
authenticator.resetOptions();
totp.resetOptions();
hotp.resetOptions();

// getting all options, with validation
// and backfilled with library defaults
const opts = authenticator.allOptions();
const opts = totp.allOptions();
const opts = hotp.allOptions();

HOTP Options

| Option | Type | Description | | ------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------- | | 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 defaults
{
  algorithm: 'sha1'
  createDigest: undefined, // to be provided via a @otplib/plugin-*
  createHmacKey: hotpCreateHmacKey,
  digits: 6,
  encoding: 'ascii',
}

TOTP Options

Note: Includes all HOTP Options

| Option | Type | Description | | ------ | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | epoch | integer | USE WITH CAUTION. Same epoch = same token.
Starting time since the UNIX epoch (seconds).
Epoch is JavaScript formatted. i.e. Date.now() or UNIX time * 1000 | | step | integer | Time step (seconds) | | window | integer,
[number, number] | 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: [past, future] |

// TOTP defaults
{
  // ...includes all HOTP defaults
  createHmacKey: totpCreateHmacKey,
  epoch: Date.now(),
  step: 30,
  window: 0,
}

Authenticator Options

Note: Includes all HOTP + TOTP Options

| Option | Type | Description | | ----------------- | -------- | ----------------------------------------------------------------------------------------------------- | | 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 defaults
  encoding: '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-*
}

Appendix

Type Definitions

TypeScript support was introduced in v10.0.0, which added type definitions over .js files.

As of v12.0.0, the library has been re-written in Typescript from the ground up.

Async Support

async support was introduced in v12.0.0 as an additional core library.

This was added as some libraries like expo.io or even the browser API (window.Crypto.subtle) started providing only async methods.

You to find more details in the core-async folder.

Browser Compatiblity

@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 bytes
HMAC-SHA256 - 32 bytes
HMAC-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.

Google Authenticator

Difference between Authenticator and TOTP

The default encoding option has been set to hex (Authenticator) instead of ascii (TOTP).

RFC3548 Base32

Note: RFC4648 obseletes RFC 3548. Any encoders following the newer specifications will work.

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.generateSecret(); // base32 encoded hex secret key
const token = authenticator.generate(secret);

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 otpauth://, which you get from authenticator.keyuri.

Google Authenticator will ignore the algorithm, digits, and step options. 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
import qrcode from 'qrcode';
import { authenticator } from '@otplib/preset-default';

const user = 'A user name, possibly an email';
const service = 'A service name';

// v11.x and above
const otpauth = authenticator.keyuri(user, service, secret);

// v10.x and below
const otpauth = authenticator.keyuri(
  encodeURIComponent(user),
  encodeURIComponent(service),
  secret
);

qrcode.toDataURL(otpauth, (err, imageUrl) => {
  if (err) {
    console.log('Error with QR');
    return;
  }
  console.log(imageUrl);
});

Note: For versions v10.x and below, keyuri does not URI encode user and 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 of a totp or authenticator token were introduced in v10.0.0.

authenticator.timeUsed(); // or totp.timeUsed();
authenticator.timeRemaining(); // 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. While otplib does not provide an expo specified package, with the re-architecture of otplib, you can now provide an expo native createDigest to the library.

Alternatively, you can make use of crypto provided by @otplib/plugin-crypto-js or the bundled browser umd module @otplib/preset-browser.

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 setup
npm run build
npx 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(secret)

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.

Contributors

Thanks goes to these wonderful people (emoji key):

Gerald Yeo
Gerald Yeo

💻 📖 🚧 ⚠️
Oliver Schneider
Oliver Schneider

📖
Marc-Aurèle DARCHE
Marc-Aurèle DARCHE

📖
Ahmed Hamdy (@shakram02)
Ahmed Hamdy (@shakram02)

📖
Tony Brix
Tony Brix

💻 📖
Plai
Plai

📖

This project follows the all-contributors specification. Contributions of any kind welcome!

License

otplib is MIT licensed