utils.js 10 KB

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