crypto-browser.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. function getGlobal() {
  8. if (typeof self !== 'undefined') {
  9. return self;
  10. }
  11. if (typeof window !== 'undefined') {
  12. return window;
  13. }
  14. if (typeof global !== 'undefined') {
  15. return global;
  16. }
  17. throw new Error('unable to locate global object');
  18. }
  19. ;
  20. const anyGlobal = getGlobal();
  21. const crypto = anyGlobal.crypto || anyGlobal.msCrypto;
  22. export function createHash(algo) {
  23. switch (algo) {
  24. case "sha256": return sha256.create();
  25. case "sha512": return sha512.create();
  26. }
  27. assertArgument(false, "invalid hashing algorithm name", "algorithm", algo);
  28. }
  29. export function createHmac(_algo, key) {
  30. const algo = ({ sha256, sha512 }[_algo]);
  31. assertArgument(algo != null, "invalid hmac algorithm", "algorithm", _algo);
  32. return hmac.create(algo, key);
  33. }
  34. export function pbkdf2Sync(password, salt, iterations, keylen, _algo) {
  35. const algo = ({ sha256, sha512 }[_algo]);
  36. assertArgument(algo != null, "invalid pbkdf2 algorithm", "algorithm", _algo);
  37. return pbkdf2(algo, password, salt, { c: iterations, dkLen: keylen });
  38. }
  39. export function randomBytes(length) {
  40. assert(crypto != null, "platform does not support secure random numbers", "UNSUPPORTED_OPERATION", {
  41. operation: "randomBytes"
  42. });
  43. assertArgument(Number.isInteger(length) && length > 0 && length <= 1024, "invalid length", "length", length);
  44. const result = new Uint8Array(length);
  45. crypto.getRandomValues(result);
  46. return result;
  47. }
  48. //# sourceMappingURL=crypto-browser.js.map