You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
313 lines
11 KiB
313 lines
11 KiB
"use strict"; |
|
/** |
|
* Utilities for hex, bytes, CSPRNG. |
|
* @module |
|
*/ |
|
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ |
|
Object.defineProperty(exports, "__esModule", { value: true }); |
|
exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.Hash = exports.nextTick = exports.swap32IfBE = exports.byteSwapIfBE = exports.swap8IfBE = exports.isLE = void 0; |
|
exports.isBytes = isBytes; |
|
exports.anumber = anumber; |
|
exports.abytes = abytes; |
|
exports.ahash = ahash; |
|
exports.aexists = aexists; |
|
exports.aoutput = aoutput; |
|
exports.u8 = u8; |
|
exports.u32 = u32; |
|
exports.clean = clean; |
|
exports.createView = createView; |
|
exports.rotr = rotr; |
|
exports.rotl = rotl; |
|
exports.byteSwap = byteSwap; |
|
exports.byteSwap32 = byteSwap32; |
|
exports.bytesToHex = bytesToHex; |
|
exports.hexToBytes = hexToBytes; |
|
exports.asyncLoop = asyncLoop; |
|
exports.utf8ToBytes = utf8ToBytes; |
|
exports.bytesToUtf8 = bytesToUtf8; |
|
exports.toBytes = toBytes; |
|
exports.kdfInputToBytes = kdfInputToBytes; |
|
exports.concatBytes = concatBytes; |
|
exports.checkOpts = checkOpts; |
|
exports.createHasher = createHasher; |
|
exports.createOptHasher = createOptHasher; |
|
exports.createXOFer = createXOFer; |
|
exports.randomBytes = randomBytes; |
|
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. |
|
// node.js versions earlier than v19 don't declare it in global scope. |
|
// For node.js, package.json#exports field mapping rewrites import |
|
// from `crypto` to `cryptoNode`, which imports native module. |
|
// Makes the utils un-importable in browsers without a bundler. |
|
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import. |
|
const crypto_1 = require("@noble/hashes/crypto"); |
|
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */ |
|
function isBytes(a) { |
|
return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array'); |
|
} |
|
/** Asserts something is positive integer. */ |
|
function anumber(n) { |
|
if (!Number.isSafeInteger(n) || n < 0) |
|
throw new Error('positive integer expected, got ' + n); |
|
} |
|
/** Asserts something is Uint8Array. */ |
|
function abytes(b, ...lengths) { |
|
if (!isBytes(b)) |
|
throw new Error('Uint8Array expected'); |
|
if (lengths.length > 0 && !lengths.includes(b.length)) |
|
throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length); |
|
} |
|
/** Asserts something is hash */ |
|
function ahash(h) { |
|
if (typeof h !== 'function' || typeof h.create !== 'function') |
|
throw new Error('Hash should be wrapped by utils.createHasher'); |
|
anumber(h.outputLen); |
|
anumber(h.blockLen); |
|
} |
|
/** Asserts a hash instance has not been destroyed / finished */ |
|
function aexists(instance, checkFinished = true) { |
|
if (instance.destroyed) |
|
throw new Error('Hash instance has been destroyed'); |
|
if (checkFinished && instance.finished) |
|
throw new Error('Hash#digest() has already been called'); |
|
} |
|
/** Asserts output is properly-sized byte array */ |
|
function aoutput(out, instance) { |
|
abytes(out); |
|
const min = instance.outputLen; |
|
if (out.length < min) { |
|
throw new Error('digestInto() expects output buffer of length at least ' + min); |
|
} |
|
} |
|
/** Cast u8 / u16 / u32 to u8. */ |
|
function u8(arr) { |
|
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); |
|
} |
|
/** Cast u8 / u16 / u32 to u32. */ |
|
function u32(arr) { |
|
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); |
|
} |
|
/** Zeroize a byte array. Warning: JS provides no guarantees. */ |
|
function clean(...arrays) { |
|
for (let i = 0; i < arrays.length; i++) { |
|
arrays[i].fill(0); |
|
} |
|
} |
|
/** Create DataView of an array for easy byte-level manipulation. */ |
|
function createView(arr) { |
|
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); |
|
} |
|
/** The rotate right (circular right shift) operation for uint32 */ |
|
function rotr(word, shift) { |
|
return (word << (32 - shift)) | (word >>> shift); |
|
} |
|
/** The rotate left (circular left shift) operation for uint32 */ |
|
function rotl(word, shift) { |
|
return (word << shift) | ((word >>> (32 - shift)) >>> 0); |
|
} |
|
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */ |
|
exports.isLE = (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)(); |
|
/** The byte swap operation for uint32 */ |
|
function byteSwap(word) { |
|
return (((word << 24) & 0xff000000) | |
|
((word << 8) & 0xff0000) | |
|
((word >>> 8) & 0xff00) | |
|
((word >>> 24) & 0xff)); |
|
} |
|
/** Conditionally byte swap if on a big-endian platform */ |
|
exports.swap8IfBE = exports.isLE |
|
? (n) => n |
|
: (n) => byteSwap(n); |
|
/** @deprecated */ |
|
exports.byteSwapIfBE = exports.swap8IfBE; |
|
/** In place byte swap for Uint32Array */ |
|
function byteSwap32(arr) { |
|
for (let i = 0; i < arr.length; i++) { |
|
arr[i] = byteSwap(arr[i]); |
|
} |
|
return arr; |
|
} |
|
exports.swap32IfBE = exports.isLE |
|
? (u) => u |
|
: byteSwap32; |
|
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex |
|
const hasHexBuiltin = /* @__PURE__ */ (() => |
|
// @ts-ignore |
|
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')(); |
|
// Array where index 0xf0 (240) is mapped to string 'f0' |
|
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); |
|
/** |
|
* Convert byte array to hex string. Uses built-in function, when available. |
|
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' |
|
*/ |
|
function bytesToHex(bytes) { |
|
abytes(bytes); |
|
// @ts-ignore |
|
if (hasHexBuiltin) |
|
return bytes.toHex(); |
|
// pre-caching improves the speed 6x |
|
let hex = ''; |
|
for (let i = 0; i < bytes.length; i++) { |
|
hex += hexes[bytes[i]]; |
|
} |
|
return hex; |
|
} |
|
// We use optimized technique to convert hex string to byte array |
|
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; |
|
function asciiToBase16(ch) { |
|
if (ch >= asciis._0 && ch <= asciis._9) |
|
return ch - asciis._0; // '2' => 50-48 |
|
if (ch >= asciis.A && ch <= asciis.F) |
|
return ch - (asciis.A - 10); // 'B' => 66-(65-10) |
|
if (ch >= asciis.a && ch <= asciis.f) |
|
return ch - (asciis.a - 10); // 'b' => 98-(97-10) |
|
return; |
|
} |
|
/** |
|
* Convert hex string to byte array. Uses built-in function, when available. |
|
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) |
|
*/ |
|
function hexToBytes(hex) { |
|
if (typeof hex !== 'string') |
|
throw new Error('hex string expected, got ' + typeof hex); |
|
// @ts-ignore |
|
if (hasHexBuiltin) |
|
return Uint8Array.fromHex(hex); |
|
const hl = hex.length; |
|
const al = hl / 2; |
|
if (hl % 2) |
|
throw new Error('hex string expected, got unpadded hex of length ' + hl); |
|
const array = new Uint8Array(al); |
|
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { |
|
const n1 = asciiToBase16(hex.charCodeAt(hi)); |
|
const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); |
|
if (n1 === undefined || n2 === undefined) { |
|
const char = hex[hi] + hex[hi + 1]; |
|
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); |
|
} |
|
array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163 |
|
} |
|
return array; |
|
} |
|
/** |
|
* There is no setImmediate in browser and setTimeout is slow. |
|
* Call of async fn will return Promise, which will be fullfiled only on |
|
* next scheduler queue processing step and this is exactly what we need. |
|
*/ |
|
const nextTick = async () => { }; |
|
exports.nextTick = nextTick; |
|
/** Returns control to thread each 'tick' ms to avoid blocking. */ |
|
async function asyncLoop(iters, tick, cb) { |
|
let ts = Date.now(); |
|
for (let i = 0; i < iters; i++) { |
|
cb(i); |
|
// Date.now() is not monotonic, so in case if clock goes backwards we return return control too |
|
const diff = Date.now() - ts; |
|
if (diff >= 0 && diff < tick) |
|
continue; |
|
await (0, exports.nextTick)(); |
|
ts += diff; |
|
} |
|
} |
|
/** |
|
* Converts string to bytes using UTF8 encoding. |
|
* @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99]) |
|
*/ |
|
function utf8ToBytes(str) { |
|
if (typeof str !== 'string') |
|
throw new Error('string expected'); |
|
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 |
|
} |
|
/** |
|
* Converts bytes to string using UTF8 encoding. |
|
* @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc' |
|
*/ |
|
function bytesToUtf8(bytes) { |
|
return new TextDecoder().decode(bytes); |
|
} |
|
/** |
|
* Normalizes (non-hex) string or Uint8Array to Uint8Array. |
|
* Warning: when Uint8Array is passed, it would NOT get copied. |
|
* Keep in mind for future mutable operations. |
|
*/ |
|
function toBytes(data) { |
|
if (typeof data === 'string') |
|
data = utf8ToBytes(data); |
|
abytes(data); |
|
return data; |
|
} |
|
/** |
|
* Helper for KDFs: consumes uint8array or string. |
|
* When string is passed, does utf8 decoding, using TextDecoder. |
|
*/ |
|
function kdfInputToBytes(data) { |
|
if (typeof data === 'string') |
|
data = utf8ToBytes(data); |
|
abytes(data); |
|
return data; |
|
} |
|
/** Copies several Uint8Arrays into one. */ |
|
function concatBytes(...arrays) { |
|
let sum = 0; |
|
for (let i = 0; i < arrays.length; i++) { |
|
const a = arrays[i]; |
|
abytes(a); |
|
sum += a.length; |
|
} |
|
const res = new Uint8Array(sum); |
|
for (let i = 0, pad = 0; i < arrays.length; i++) { |
|
const a = arrays[i]; |
|
res.set(a, pad); |
|
pad += a.length; |
|
} |
|
return res; |
|
} |
|
function checkOpts(defaults, opts) { |
|
if (opts !== undefined && {}.toString.call(opts) !== '[object Object]') |
|
throw new Error('options should be object or undefined'); |
|
const merged = Object.assign(defaults, opts); |
|
return merged; |
|
} |
|
/** For runtime check if class implements interface */ |
|
class Hash { |
|
} |
|
exports.Hash = Hash; |
|
/** Wraps hash function, creating an interface on top of it */ |
|
function createHasher(hashCons) { |
|
const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); |
|
const tmp = hashCons(); |
|
hashC.outputLen = tmp.outputLen; |
|
hashC.blockLen = tmp.blockLen; |
|
hashC.create = () => hashCons(); |
|
return hashC; |
|
} |
|
function createOptHasher(hashCons) { |
|
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); |
|
const tmp = hashCons({}); |
|
hashC.outputLen = tmp.outputLen; |
|
hashC.blockLen = tmp.blockLen; |
|
hashC.create = (opts) => hashCons(opts); |
|
return hashC; |
|
} |
|
function createXOFer(hashCons) { |
|
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); |
|
const tmp = hashCons({}); |
|
hashC.outputLen = tmp.outputLen; |
|
hashC.blockLen = tmp.blockLen; |
|
hashC.create = (opts) => hashCons(opts); |
|
return hashC; |
|
} |
|
exports.wrapConstructor = createHasher; |
|
exports.wrapConstructorWithOpts = createOptHasher; |
|
exports.wrapXOFConstructorWithOpts = createXOFer; |
|
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */ |
|
function randomBytes(bytesLength = 32) { |
|
if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') { |
|
return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); |
|
} |
|
// Legacy Node.js compatibility |
|
if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === 'function') { |
|
return Uint8Array.from(crypto_1.crypto.randomBytes(bytesLength)); |
|
} |
|
throw new Error('crypto.getRandomValues must be defined'); |
|
} |
|
//# sourceMappingURL=utils.js.map
|