13 lines
661 B
TypeScript
13 lines
661 B
TypeScript
import { createHmac } from 'crypto';
|
|
|
|
export function totp(secret: string, step: number) {
|
|
let bits = ''; for (const c of secret.toUpperCase().replace(/=|\s/g, '')) {
|
|
const n = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.indexOf(c); if (n < 0) throw new Error('Invalid TOTP secret');
|
|
bits += n.toString(2).padStart(5, '0');
|
|
}
|
|
const key = Buffer.from(bits.match(/.{8}/g)!.map(b => parseInt(b, 2)));
|
|
const counter = Buffer.alloc(8); counter.writeBigUInt64BE(BigInt(step));
|
|
const hash = createHmac('sha1', key).update(counter).digest(); const offset = hash[19] & 15;
|
|
return String((hash.readUInt32BE(offset) & 0x7fffffff) % 1000000).padStart(6, '0');
|
|
}
|