crypto-browser.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. /* Browser Crypto Shims */
  3. Object.defineProperty(exports, "__esModule", { value: true });
  4. exports.randomBytes = exports.pbkdf2Sync = exports.createHmac = exports.createHash = void 0;
  5. const hmac_1 = require("@noble/hashes/hmac");
  6. const pbkdf2_1 = require("@noble/hashes/pbkdf2");
  7. const sha256_1 = require("@noble/hashes/sha256");
  8. const sha512_1 = require("@noble/hashes/sha512");
  9. const index_js_1 = require("../utils/index.js");
  10. function getGlobal() {
  11. if (typeof self !== 'undefined') {
  12. return self;
  13. }
  14. if (typeof window !== 'undefined') {
  15. return window;
  16. }
  17. if (typeof global !== 'undefined') {
  18. return global;
  19. }
  20. throw new Error('unable to locate global object');
  21. }
  22. ;
  23. const anyGlobal = getGlobal();
  24. const crypto = anyGlobal.crypto || anyGlobal.msCrypto;
  25. function createHash(algo) {
  26. switch (algo) {
  27. case "sha256": return sha256_1.sha256.create();
  28. case "sha512": return sha512_1.sha512.create();
  29. }
  30. (0, index_js_1.assertArgument)(false, "invalid hashing algorithm name", "algorithm", algo);
  31. }
  32. exports.createHash = createHash;
  33. function createHmac(_algo, key) {
  34. const algo = ({ sha256: sha256_1.sha256, sha512: sha512_1.sha512 }[_algo]);
  35. (0, index_js_1.assertArgument)(algo != null, "invalid hmac algorithm", "algorithm", _algo);
  36. return hmac_1.hmac.create(algo, key);
  37. }
  38. exports.createHmac = createHmac;
  39. function pbkdf2Sync(password, salt, iterations, keylen, _algo) {
  40. const algo = ({ sha256: sha256_1.sha256, sha512: sha512_1.sha512 }[_algo]);
  41. (0, index_js_1.assertArgument)(algo != null, "invalid pbkdf2 algorithm", "algorithm", _algo);
  42. return (0, pbkdf2_1.pbkdf2)(algo, password, salt, { c: iterations, dkLen: keylen });
  43. }
  44. exports.pbkdf2Sync = pbkdf2Sync;
  45. function randomBytes(length) {
  46. (0, index_js_1.assert)(crypto != null, "platform does not support secure random numbers", "UNSUPPORTED_OPERATION", {
  47. operation: "randomBytes"
  48. });
  49. (0, index_js_1.assertArgument)(Number.isInteger(length) && length > 0 && length <= 1024, "invalid length", "length", length);
  50. const result = new Uint8Array(length);
  51. crypto.getRandomValues(result);
  52. return result;
  53. }
  54. exports.randomBytes = randomBytes;
  55. //# sourceMappingURL=crypto-browser.js.map