utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. "use strict";
  2. /**
  3. * Utilities for hex, bytes, CSPRNG.
  4. * @module
  5. */
  6. /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  7. Object.defineProperty(exports, "__esModule", { value: true });
  8. exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.Hash = exports.nextTick = exports.swap32IfBE = exports.byteSwapIfBE = exports.swap8IfBE = exports.isLE = void 0;
  9. exports.isBytes = isBytes;
  10. exports.anumber = anumber;
  11. exports.abytes = abytes;
  12. exports.ahash = ahash;
  13. exports.aexists = aexists;
  14. exports.aoutput = aoutput;
  15. exports.u8 = u8;
  16. exports.u32 = u32;
  17. exports.clean = clean;
  18. exports.createView = createView;
  19. exports.rotr = rotr;
  20. exports.rotl = rotl;
  21. exports.byteSwap = byteSwap;
  22. exports.byteSwap32 = byteSwap32;
  23. exports.bytesToHex = bytesToHex;
  24. exports.hexToBytes = hexToBytes;
  25. exports.asyncLoop = asyncLoop;
  26. exports.utf8ToBytes = utf8ToBytes;
  27. exports.bytesToUtf8 = bytesToUtf8;
  28. exports.toBytes = toBytes;
  29. exports.kdfInputToBytes = kdfInputToBytes;
  30. exports.concatBytes = concatBytes;
  31. exports.checkOpts = checkOpts;
  32. exports.createHasher = createHasher;
  33. exports.createOptHasher = createOptHasher;
  34. exports.createXOFer = createXOFer;
  35. exports.randomBytes = randomBytes;
  36. // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
  37. // node.js versions earlier than v19 don't declare it in global scope.
  38. // For node.js, package.json#exports field mapping rewrites import
  39. // from `crypto` to `cryptoNode`, which imports native module.
  40. // Makes the utils un-importable in browsers without a bundler.
  41. // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
  42. const crypto_1 = require("@noble/hashes/crypto");
  43. /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
  44. function isBytes(a) {
  45. return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
  46. }
  47. /** Asserts something is positive integer. */
  48. function anumber(n) {
  49. if (!Number.isSafeInteger(n) || n < 0)
  50. throw new Error('positive integer expected, got ' + n);
  51. }
  52. /** Asserts something is Uint8Array. */
  53. function abytes(b, ...lengths) {
  54. if (!isBytes(b))
  55. throw new Error('Uint8Array expected');
  56. if (lengths.length > 0 && !lengths.includes(b.length))
  57. throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
  58. }
  59. /** Asserts something is hash */
  60. function ahash(h) {
  61. if (typeof h !== 'function' || typeof h.create !== 'function')
  62. throw new Error('Hash should be wrapped by utils.createHasher');
  63. anumber(h.outputLen);
  64. anumber(h.blockLen);
  65. }
  66. /** Asserts a hash instance has not been destroyed / finished */
  67. function aexists(instance, checkFinished = true) {
  68. if (instance.destroyed)
  69. throw new Error('Hash instance has been destroyed');
  70. if (checkFinished && instance.finished)
  71. throw new Error('Hash#digest() has already been called');
  72. }
  73. /** Asserts output is properly-sized byte array */
  74. function aoutput(out, instance) {
  75. abytes(out);
  76. const min = instance.outputLen;
  77. if (out.length < min) {
  78. throw new Error('digestInto() expects output buffer of length at least ' + min);
  79. }
  80. }
  81. /** Cast u8 / u16 / u32 to u8. */
  82. function u8(arr) {
  83. return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
  84. }
  85. /** Cast u8 / u16 / u32 to u32. */
  86. function u32(arr) {
  87. return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
  88. }
  89. /** Zeroize a byte array. Warning: JS provides no guarantees. */
  90. function clean(...arrays) {
  91. for (let i = 0; i < arrays.length; i++) {
  92. arrays[i].fill(0);
  93. }
  94. }
  95. /** Create DataView of an array for easy byte-level manipulation. */
  96. function createView(arr) {
  97. return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
  98. }
  99. /** The rotate right (circular right shift) operation for uint32 */
  100. function rotr(word, shift) {
  101. return (word << (32 - shift)) | (word >>> shift);
  102. }
  103. /** The rotate left (circular left shift) operation for uint32 */
  104. function rotl(word, shift) {
  105. return (word << shift) | ((word >>> (32 - shift)) >>> 0);
  106. }
  107. /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
  108. exports.isLE = (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
  109. /** The byte swap operation for uint32 */
  110. function byteSwap(word) {
  111. return (((word << 24) & 0xff000000) |
  112. ((word << 8) & 0xff0000) |
  113. ((word >>> 8) & 0xff00) |
  114. ((word >>> 24) & 0xff));
  115. }
  116. /** Conditionally byte swap if on a big-endian platform */
  117. exports.swap8IfBE = exports.isLE
  118. ? (n) => n
  119. : (n) => byteSwap(n);
  120. /** @deprecated */
  121. exports.byteSwapIfBE = exports.swap8IfBE;
  122. /** In place byte swap for Uint32Array */
  123. function byteSwap32(arr) {
  124. for (let i = 0; i < arr.length; i++) {
  125. arr[i] = byteSwap(arr[i]);
  126. }
  127. return arr;
  128. }
  129. exports.swap32IfBE = exports.isLE
  130. ? (u) => u
  131. : byteSwap32;
  132. // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
  133. const hasHexBuiltin = /* @__PURE__ */ (() =>
  134. // @ts-ignore
  135. typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
  136. // Array where index 0xf0 (240) is mapped to string 'f0'
  137. const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
  138. /**
  139. * Convert byte array to hex string. Uses built-in function, when available.
  140. * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
  141. */
  142. function bytesToHex(bytes) {
  143. abytes(bytes);
  144. // @ts-ignore
  145. if (hasHexBuiltin)
  146. return bytes.toHex();
  147. // pre-caching improves the speed 6x
  148. let hex = '';
  149. for (let i = 0; i < bytes.length; i++) {
  150. hex += hexes[bytes[i]];
  151. }
  152. return hex;
  153. }
  154. // We use optimized technique to convert hex string to byte array
  155. const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
  156. function asciiToBase16(ch) {
  157. if (ch >= asciis._0 && ch <= asciis._9)
  158. return ch - asciis._0; // '2' => 50-48
  159. if (ch >= asciis.A && ch <= asciis.F)
  160. return ch - (asciis.A - 10); // 'B' => 66-(65-10)
  161. if (ch >= asciis.a && ch <= asciis.f)
  162. return ch - (asciis.a - 10); // 'b' => 98-(97-10)
  163. return;
  164. }
  165. /**
  166. * Convert hex string to byte array. Uses built-in function, when available.
  167. * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
  168. */
  169. function hexToBytes(hex) {
  170. if (typeof hex !== 'string')
  171. throw new Error('hex string expected, got ' + typeof hex);
  172. // @ts-ignore
  173. if (hasHexBuiltin)
  174. return Uint8Array.fromHex(hex);
  175. const hl = hex.length;
  176. const al = hl / 2;
  177. if (hl % 2)
  178. throw new Error('hex string expected, got unpadded hex of length ' + hl);
  179. const array = new Uint8Array(al);
  180. for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
  181. const n1 = asciiToBase16(hex.charCodeAt(hi));
  182. const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
  183. if (n1 === undefined || n2 === undefined) {
  184. const char = hex[hi] + hex[hi + 1];
  185. throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
  186. }
  187. array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
  188. }
  189. return array;
  190. }
  191. /**
  192. * There is no setImmediate in browser and setTimeout is slow.
  193. * Call of async fn will return Promise, which will be fullfiled only on
  194. * next scheduler queue processing step and this is exactly what we need.
  195. */
  196. const nextTick = async () => { };
  197. exports.nextTick = nextTick;
  198. /** Returns control to thread each 'tick' ms to avoid blocking. */
  199. async function asyncLoop(iters, tick, cb) {
  200. let ts = Date.now();
  201. for (let i = 0; i < iters; i++) {
  202. cb(i);
  203. // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
  204. const diff = Date.now() - ts;
  205. if (diff >= 0 && diff < tick)
  206. continue;
  207. await (0, exports.nextTick)();
  208. ts += diff;
  209. }
  210. }
  211. /**
  212. * Converts string to bytes using UTF8 encoding.
  213. * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
  214. */
  215. function utf8ToBytes(str) {
  216. if (typeof str !== 'string')
  217. throw new Error('string expected');
  218. return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
  219. }
  220. /**
  221. * Converts bytes to string using UTF8 encoding.
  222. * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
  223. */
  224. function bytesToUtf8(bytes) {
  225. return new TextDecoder().decode(bytes);
  226. }
  227. /**
  228. * Normalizes (non-hex) string or Uint8Array to Uint8Array.
  229. * Warning: when Uint8Array is passed, it would NOT get copied.
  230. * Keep in mind for future mutable operations.
  231. */
  232. function toBytes(data) {
  233. if (typeof data === 'string')
  234. data = utf8ToBytes(data);
  235. abytes(data);
  236. return data;
  237. }
  238. /**
  239. * Helper for KDFs: consumes uint8array or string.
  240. * When string is passed, does utf8 decoding, using TextDecoder.
  241. */
  242. function kdfInputToBytes(data) {
  243. if (typeof data === 'string')
  244. data = utf8ToBytes(data);
  245. abytes(data);
  246. return data;
  247. }
  248. /** Copies several Uint8Arrays into one. */
  249. function concatBytes(...arrays) {
  250. let sum = 0;
  251. for (let i = 0; i < arrays.length; i++) {
  252. const a = arrays[i];
  253. abytes(a);
  254. sum += a.length;
  255. }
  256. const res = new Uint8Array(sum);
  257. for (let i = 0, pad = 0; i < arrays.length; i++) {
  258. const a = arrays[i];
  259. res.set(a, pad);
  260. pad += a.length;
  261. }
  262. return res;
  263. }
  264. function checkOpts(defaults, opts) {
  265. if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
  266. throw new Error('options should be object or undefined');
  267. const merged = Object.assign(defaults, opts);
  268. return merged;
  269. }
  270. /** For runtime check if class implements interface */
  271. class Hash {
  272. }
  273. exports.Hash = Hash;
  274. /** Wraps hash function, creating an interface on top of it */
  275. function createHasher(hashCons) {
  276. const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
  277. const tmp = hashCons();
  278. hashC.outputLen = tmp.outputLen;
  279. hashC.blockLen = tmp.blockLen;
  280. hashC.create = () => hashCons();
  281. return hashC;
  282. }
  283. function createOptHasher(hashCons) {
  284. const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
  285. const tmp = hashCons({});
  286. hashC.outputLen = tmp.outputLen;
  287. hashC.blockLen = tmp.blockLen;
  288. hashC.create = (opts) => hashCons(opts);
  289. return hashC;
  290. }
  291. function createXOFer(hashCons) {
  292. const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
  293. const tmp = hashCons({});
  294. hashC.outputLen = tmp.outputLen;
  295. hashC.blockLen = tmp.blockLen;
  296. hashC.create = (opts) => hashCons(opts);
  297. return hashC;
  298. }
  299. exports.wrapConstructor = createHasher;
  300. exports.wrapConstructorWithOpts = createOptHasher;
  301. exports.wrapXOFConstructorWithOpts = createXOFer;
  302. /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
  303. function randomBytes(bytesLength = 32) {
  304. if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') {
  305. return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
  306. }
  307. // Legacy Node.js compatibility
  308. if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === 'function') {
  309. return Uint8Array.from(crypto_1.crypto.randomBytes(bytesLength));
  310. }
  311. throw new Error('crypto.getRandomValues must be defined');
  312. }
  313. //# sourceMappingURL=utils.js.map