sha2.ts 1.9 KB

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