crypto-browser.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* Browser Crypto Shims */
  2. import { hmac } from "@noble/hashes/hmac";
  3. import { pbkdf2 } from "@noble/hashes/pbkdf2";
  4. import { sha256 } from "@noble/hashes/sha256";
  5. import { sha512 } from "@noble/hashes/sha512";
  6. import { assert, assertArgument } from "../utils/index.js";
  7. declare global {
  8. interface Window { }
  9. const window: Window;
  10. const self: Window;
  11. }
  12. function getGlobal(): any {
  13. if (typeof self !== 'undefined') { return self; }
  14. if (typeof window !== 'undefined') { return window; }
  15. if (typeof global !== 'undefined') { return global; }
  16. throw new Error('unable to locate global object');
  17. };
  18. const anyGlobal = getGlobal();
  19. const crypto: any = anyGlobal.crypto || anyGlobal.msCrypto;
  20. export interface CryptoHasher {
  21. update(data: Uint8Array): CryptoHasher;
  22. digest(): Uint8Array;
  23. }
  24. export function createHash(algo: string): CryptoHasher {
  25. switch (algo) {
  26. case "sha256": return sha256.create();
  27. case "sha512": return sha512.create();
  28. }
  29. assertArgument(false, "invalid hashing algorithm name", "algorithm", algo);
  30. }
  31. export function createHmac(_algo: string, key: Uint8Array): CryptoHasher {
  32. const algo = ({ sha256, sha512 }[_algo]);
  33. assertArgument(algo != null, "invalid hmac algorithm", "algorithm", _algo);
  34. return hmac.create(algo, key);
  35. }
  36. export function pbkdf2Sync(password: Uint8Array, salt: Uint8Array, iterations: number, keylen: number, _algo: "sha256" | "sha512"): Uint8Array {
  37. const algo = ({ sha256, sha512 }[_algo]);
  38. assertArgument(algo != null, "invalid pbkdf2 algorithm", "algorithm", _algo);
  39. return pbkdf2(algo, password, salt, { c: iterations, dkLen: keylen });
  40. }
  41. export function randomBytes(length: number): Uint8Array {
  42. assert(crypto != null, "platform does not support secure random numbers", "UNSUPPORTED_OPERATION", {
  43. operation: "randomBytes" });
  44. assertArgument(Number.isInteger(length) && length > 0 && length <= 1024, "invalid length", "length", length);
  45. const result = new Uint8Array(length);
  46. crypto.getRandomValues(result);
  47. return result;
  48. }