a function to generate a one-time use passcode otp in typescript

Here's an example of a function to generate a one-time use passcode (OTP) in TypeScript using the Time-Based One-Time Password (TOTP) algorithm and the crypto module for encryption:

index.ts
import * as crypto from 'crypto';

function generateOTP(secret: string, window: number = 30): string {
  const epoch = Math.round(Date.now() / 1000);
  const timeSteps = Math.floor(epoch / window);
  const timeBuffer = Buffer.alloc(8);
  for (let i = 7; i >= 0; i--) {
    timeBuffer.writeUInt8(timeSteps & 0xff, i);
    timeSteps >>= 8;
  }

  const hmac = crypto.createHmac('sha1', secret).update(timeBuffer).digest();
  const start = hmac[hmac.length - 1] & 0x0f;
  const codeData = hmac.slice(start, start + 4);

  const fullcode = codeData.readUInt32BE(0) & 0x7fffffff;
  const code = fullcode % 1000000;

  return code.toString().padStart(6, '0');
}
656 chars
21 lines

Here, secret is a string that you should keep securely and distribute to the users or devices that you want to generate OTPs for. window is an optional parameter specifying the time window of each OTP, in seconds. By default, it's set to 30 seconds as recommended by the TOTP algorithm.

To generate an OTP, simply call the generateOTP function with the secret and optionally the window. It will return a six-digit alphanumeric string that serves as the OTP.

gistlibby LogSnag