keccak.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * Cryptographic hashing functions
  3. *
  4. * @_subsection: api/crypto:Hash Functions [about-crypto-hashing]
  5. */
  6. import { keccak_256 } from "@noble/hashes/sha3";
  7. import { getBytes, hexlify } from "../utils/index.js";
  8. import type { BytesLike } from "../utils/index.js";
  9. let locked = false;
  10. const _keccak256 = function(data: Uint8Array): Uint8Array {
  11. return keccak_256(data);
  12. }
  13. let __keccak256: (data: Uint8Array) => BytesLike = _keccak256;
  14. /**
  15. * Compute the cryptographic KECCAK256 hash of %%data%%.
  16. *
  17. * The %%data%% **must** be a data representation, to compute the
  18. * hash of UTF-8 data use the [[id]] function.
  19. *
  20. * @returns DataHexstring
  21. * @example:
  22. * keccak256("0x")
  23. * //_result:
  24. *
  25. * keccak256("0x1337")
  26. * //_result:
  27. *
  28. * keccak256(new Uint8Array([ 0x13, 0x37 ]))
  29. * //_result:
  30. *
  31. * // Strings are assumed to be DataHexString, otherwise it will
  32. * // throw. To hash UTF-8 data, see the note above.
  33. * keccak256("Hello World")
  34. * //_error:
  35. */
  36. export function keccak256(_data: BytesLike): string {
  37. const data = getBytes(_data, "data");
  38. return hexlify(__keccak256(data));
  39. }
  40. keccak256._ = _keccak256;
  41. keccak256.lock = function(): void { locked = true; }
  42. keccak256.register = function(func: (data: Uint8Array) => BytesLike) {
  43. if (locked) { throw new TypeError("keccak256 is locked"); }
  44. __keccak256 = func;
  45. }
  46. Object.freeze(keccak256);