ethers.js/lib.esm/crypto/crypto-browser.js

48 lines
1.8 KiB
JavaScript
Raw Normal View History

2022-09-05 23:57:11 +03:00
/* Browser Crypto Shims */
import { hmac } from "@noble/hashes/hmac";
import { pbkdf2 } from "@noble/hashes/pbkdf2";
import { sha256 } from "@noble/hashes/sha256";
import { sha512 } from "@noble/hashes/sha512";
2022-11-09 10:57:02 +03:00
import { assert, assertArgument } from "../utils/index.js";
2022-09-05 23:57:11 +03:00
function getGlobal() {
if (typeof self !== 'undefined') {
return self;
}
if (typeof window !== 'undefined') {
return window;
}
if (typeof global !== 'undefined') {
return global;
}
throw new Error('unable to locate global object');
}
;
const anyGlobal = getGlobal();
const crypto = anyGlobal.crypto || anyGlobal.msCrypto;
export function createHash(algo) {
switch (algo) {
case "sha256": return sha256.create();
case "sha512": return sha512.create();
}
2022-11-09 10:57:02 +03:00
assertArgument(false, "invalid hashing algorithm name", "algorithm", algo);
2022-09-05 23:57:11 +03:00
}
export function createHmac(_algo, key) {
const algo = ({ sha256, sha512 }[_algo]);
2022-11-09 10:57:02 +03:00
assertArgument(algo != null, "invalid hmac algorithm", "algorithm", _algo);
2022-09-05 23:57:11 +03:00
return hmac.create(algo, key);
}
export function pbkdf2Sync(password, salt, iterations, keylen, _algo) {
const algo = ({ sha256, sha512 }[_algo]);
2022-11-09 10:57:02 +03:00
assertArgument(algo != null, "invalid pbkdf2 algorithm", "algorithm", _algo);
2022-09-05 23:57:11 +03:00
return pbkdf2(algo, password, salt, { c: iterations, dkLen: keylen });
}
export function randomBytes(length) {
2022-11-09 10:57:02 +03:00
assert(crypto != null, "platform does not support secure random numbers", "UNSUPPORTED_OPERATION", {
operation: "randomBytes"
});
assertArgument(Number.isInteger(length) && length > 0 && length <= 1024, "invalid length", "length", length);
2022-09-05 23:57:11 +03:00
const result = new Uint8Array(length);
crypto.getRandomValues(result);
return result;
}
//# sourceMappingURL=crypto-browser.js.map