hmac.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. let locked = false;
  12. const _computeHmac = function (algorithm, key, data) {
  13. return createHmac(algorithm, key).update(data).digest();
  14. };
  15. let __computeHmac = _computeHmac;
  16. /**
  17. * Return the HMAC for %%data%% using the %%key%% key with the underlying
  18. * %%algo%% used for compression.
  19. *
  20. * @example:
  21. * key = id("some-secret")
  22. *
  23. * // Compute the HMAC
  24. * computeHmac("sha256", key, "0x1337")
  25. * //_result:
  26. *
  27. * // To compute the HMAC of UTF-8 data, the data must be
  28. * // converted to UTF-8 bytes
  29. * computeHmac("sha256", key, toUtf8Bytes("Hello World"))
  30. * //_result:
  31. *
  32. */
  33. export function computeHmac(algorithm, _key, _data) {
  34. const key = getBytes(_key, "key");
  35. const data = getBytes(_data, "data");
  36. return hexlify(__computeHmac(algorithm, key, data));
  37. }
  38. computeHmac._ = _computeHmac;
  39. computeHmac.lock = function () { locked = true; };
  40. computeHmac.register = function (func) {
  41. if (locked) {
  42. throw new Error("computeHmac is locked");
  43. }
  44. __computeHmac = func;
  45. };
  46. Object.freeze(computeHmac);
  47. //# sourceMappingURL=hmac.js.map