What is totp-generator?
The totp-generator npm package is used to generate Time-based One-Time Passwords (TOTP). This is commonly used for two-factor authentication (2FA) to enhance security by providing a second layer of authentication.
What are totp-generator's main functionalities?
Generate TOTP
This feature allows you to generate a TOTP using a shared secret. The generated token is time-based and changes every 30 seconds by default.
const totp = require('totp-generator');
const secret = 'JBSWY3DPEHPK3PXP';
const token = totp(secret);
console.log(token);
Custom Time Step
This feature allows you to customize the time step for the TOTP generation. In this example, the token changes every 60 seconds instead of the default 30 seconds.
const totp = require('totp-generator');
const secret = 'JBSWY3DPEHPK3PXP';
const token = totp(secret, { time: 60 });
console.log(token);
Custom Digits
This feature allows you to customize the number of digits in the generated TOTP. In this example, the token has 8 digits instead of the default 6 digits.
const totp = require('totp-generator');
const secret = 'JBSWY3DPEHPK3PXP';
const token = totp(secret, { digits: 8 });
console.log(token);
Other packages similar to totp-generator
otplib
otplib is a comprehensive library for generating and validating both TOTP and HOTP (HMAC-based One-Time Passwords). It offers more configuration options and supports both TOTP and HOTP, making it more versatile compared to totp-generator.
speakeasy
speakeasy is another popular library for generating and verifying TOTP and HOTP. It provides a wide range of features including QR code generation for easy setup with authenticator apps. It is more feature-rich compared to totp-generator.
notp
notp is a minimalistic library for generating and verifying TOTP and HOTP. It is lightweight and easy to use, but it lacks some of the advanced features found in otplib and speakeasy. It is simpler but less versatile compared to totp-generator.
totp-generator
totp-generator lets you generate TOTP tokens from a TOTP key
How to use
import { TOTP } from "totp-generator"
const { otp, expires } = TOTP.generate("JBSWY3DPEHPK3PXP")
console.log(otp)
Default token settings
- SHA-1
- 30-second epoch interval
- 6-digit tokens
Custom token settings
Settings can be provided as an optional second parameter:
import { TOTP } from "totp-generator"
const { otp } = TOTP.generate("JBSWY3DPEHPK3PXP", { digits: 8 })
console.log(token)
const { otp } = TOTP.generate("JBSWY3DPEHPK3PXP", { algorithm: "SHA-512" })
console.log(token)
const { otp } = TOTP.generate("JBSWY3DPEHPK3PXP", { period: 60 })
console.log(token)
const { otp } = TOTP.generate("JBSWY3DPEHPK3PXP", { timestamp: 1465324707000 })
console.log(token)
const { otp } = TOTP.generate("JBSWY3DPEHPK3PXP", {
digits: 8,
algorithm: "SHA-512",
period: 60,
timestamp: 1465324707000,
})
console.log(token)
What do I use this library for?
- TOTP generation
- E2E tests (where you need to login with 2-factor authentication)