sha2.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { createHash } from "./crypto.js";
  2. import { getBytes, hexlify } from "../utils/index.js";
  3. const _sha256 = function (data) {
  4. return createHash("sha256").update(data).digest();
  5. };
  6. const _sha512 = function (data) {
  7. return createHash("sha512").update(data).digest();
  8. };
  9. let __sha256 = _sha256;
  10. let __sha512 = _sha512;
  11. let locked256 = false, locked512 = false;
  12. /**
  13. * Compute the cryptographic SHA2-256 hash of %%data%%.
  14. *
  15. * @_docloc: api/crypto:Hash Functions
  16. * @returns DataHexstring
  17. *
  18. * @example:
  19. * sha256("0x")
  20. * //_result:
  21. *
  22. * sha256("0x1337")
  23. * //_result:
  24. *
  25. * sha256(new Uint8Array([ 0x13, 0x37 ]))
  26. * //_result:
  27. *
  28. */
  29. export function sha256(_data) {
  30. const data = getBytes(_data, "data");
  31. return hexlify(__sha256(data));
  32. }
  33. sha256._ = _sha256;
  34. sha256.lock = function () { locked256 = true; };
  35. sha256.register = function (func) {
  36. if (locked256) {
  37. throw new Error("sha256 is locked");
  38. }
  39. __sha256 = func;
  40. };
  41. Object.freeze(sha256);
  42. /**
  43. * Compute the cryptographic SHA2-512 hash of %%data%%.
  44. *
  45. * @_docloc: api/crypto:Hash Functions
  46. * @returns DataHexstring
  47. *
  48. * @example:
  49. * sha512("0x")
  50. * //_result:
  51. *
  52. * sha512("0x1337")
  53. * //_result:
  54. *
  55. * sha512(new Uint8Array([ 0x13, 0x37 ]))
  56. * //_result:
  57. */
  58. export function sha512(_data) {
  59. const data = getBytes(_data, "data");
  60. return hexlify(__sha512(data));
  61. }
  62. sha512._ = _sha512;
  63. sha512.lock = function () { locked512 = true; };
  64. sha512.register = function (func) {
  65. if (locked512) {
  66. throw new Error("sha512 is locked");
  67. }
  68. __sha512 = func;
  69. };
  70. Object.freeze(sha256);
  71. //# sourceMappingURL=sha2.js.map