hmac.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * An **HMAC** enables verification that a given key was used
  3. * to authenticate a payload.
  4. *
  5. * See: [[link-wiki-hmac]]
  6. *
  7. * @_subsection: api/crypto:HMAC [about-hmac]
  8. */
  9. import { createHmac } from "./crypto.js";
  10. import { getBytes, hexlify } from "../utils/index.js";
  11. import type { BytesLike } from "../utils/index.js";
  12. let locked = false;
  13. const _computeHmac = function(algorithm: "sha256" | "sha512", key: Uint8Array, data: Uint8Array): BytesLike {
  14. return createHmac(algorithm, key).update(data).digest();
  15. }
  16. let __computeHmac = _computeHmac;
  17. /**
  18. * Return the HMAC for %%data%% using the %%key%% key with the underlying
  19. * %%algo%% used for compression.
  20. *
  21. * @example:
  22. * key = id("some-secret")
  23. *
  24. * // Compute the HMAC
  25. * computeHmac("sha256", key, "0x1337")
  26. * //_result:
  27. *
  28. * // To compute the HMAC of UTF-8 data, the data must be
  29. * // converted to UTF-8 bytes
  30. * computeHmac("sha256", key, toUtf8Bytes("Hello World"))
  31. * //_result:
  32. *
  33. */
  34. export function computeHmac(algorithm: "sha256" | "sha512", _key: BytesLike, _data: BytesLike): string {
  35. const key = getBytes(_key, "key");
  36. const data = getBytes(_data, "data");
  37. return hexlify(__computeHmac(algorithm, key, data));
  38. }
  39. computeHmac._ = _computeHmac;
  40. computeHmac.lock = function() { locked = true; }
  41. computeHmac.register = function(func: (algorithm: "sha256" | "sha512", key: Uint8Array, data: Uint8Array) => BytesLike) {
  42. if (locked) { throw new Error("computeHmac is locked"); }
  43. __computeHmac = func;
  44. }
  45. Object.freeze(computeHmac);