@nithin-sivakumar/genotp
Version:
A lightweight and secure OTP (One-Time Password) generator for JavaScript with customizable features like length, character set, prefix, suffix, and base64 encoding.
57 lines (47 loc) • 1.77 kB
JavaScript
import crypto from "crypto";
class OTPGenerator {
/**
* Generate an OTP with secure randomness.
* @param {number} length - Length of the OTP (default: 6).
* @param {string} mode - Mode of OTP generation: 'numeric', 'alphanumeric', or 'custom' (default: 'numeric').
* @param {string} charSet - Custom character set to use (only for 'custom' mode).
* @param {string} prefix - Optional prefix to be added to the OTP (default: "").
* @param {string} suffix - Optional suffix to be added to the OTP (default: "").
* @param {boolean} base64Encode - Whether to return the OTP in base64 encoding (default: false).
* @returns {string} The generated OTP.
*/
static generate(
length = 6,
mode = "numeric",
charSet = "",
prefix = "",
suffix = "",
base64Encode = false
) {
const predefinedCharSets = {
numeric: "0123456789",
alphanumeric: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
custom: charSet,
};
const finalCharSet = predefinedCharSets[mode] || predefinedCharSets.numeric;
if (
!finalCharSet ||
typeof finalCharSet !== "string" ||
finalCharSet.length === 0
) {
throw new Error("Invalid character set or mode.");
}
if (length <= 0) {
throw new Error("Length must be greater than 0.");
}
const otp = Array.from(crypto.randomFillSync(new Uint8Array(length)))
.map((byte) => finalCharSet[byte % finalCharSet.length])
.join("");
const fullOtp = `${prefix}${otp}${suffix}`;
if (base64Encode) {
return Buffer.from(fullOtp).toString("base64"); // Return base64 encoded OTP
}
return fullOtp;
}
}
export const generate = OTPGenerator.generate;