UNPKG

xotp

Version:

One-Time Password (HOTP/TOTP) library for Node.js, Deno and Bun, with support for Google Authenticator.

44 lines (43 loc) 1.29 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.uintEncode = uintEncode; exports.uintDecode = uintDecode; exports.uint64Encode = uint64Encode; exports.uint64Decode = uint64Decode; function uintEncode(num) { const bytes = new Uint8Array(8).fill(0); for (let i = 7; i >= 0; i--) { bytes[i] = num & 0xff; // Shift 8 bits to the right and rounds down the result! // NOTE: Right shift (>>) operator only works on 32-bit // integers, but `num` could be an 8-byte integer! num = (num / Math.pow(2, 8)) | 0; } return bytes; } function uintDecode(bytes) { let num = 0; let arr = bytes; if (bytes instanceof Buffer) { arr = new Uint8Array(bytes); } for (let i = 0; i < arr.length; i++) { num = num * Math.pow(2, 8) + arr[i]; } return num; } function uint64Encode(num) { let int64Num = BigInt(num); const bytes = new Uint8Array(8); const dataView = new DataView(bytes.buffer); dataView.setBigInt64(0, int64Num); return bytes; } function uint64Decode(bytes) { let arr = bytes; if (bytes instanceof Buffer) { arr = new Uint8Array(bytes); } const dataView = new DataView(arr.buffer); return dataView.getBigUint64(0); }