one
Version:
One is a React framework for web, iOS, and Android apps.
43 lines (40 loc) • 1.47 kB
JavaScript
import { bytesToBase64, bytesToHex, utf8Encode } from "./bytes.mjs";
import { bufferSourceRange } from "./digest.mjs";
const DIGEST_ALGORITHMS = [
"MD5",
"SHA-1",
"SHA-256",
"SHA-384",
"SHA-512"
];
function assertDigestAlgorithm(algorithm, verb) {
if (!DIGEST_ALGORITHMS.includes(algorithm)) {
throw new Error(`${verb}: unknown algorithm ${JSON.stringify(algorithm)}. Expected one of: ${DIGEST_ALGORITHMS.join(", ")}`);
}
}
function createDigestApi(source) {
async function digest(algorithm, data) {
assertDigestAlgorithm(algorithm, "Crypto.digest");
const { buffer, offset, length } = bufferSourceRange(data, "Crypto.digest");
return source(algorithm, buffer, offset, length);
}
async function digestString(algorithm, data, options = {}) {
assertDigestAlgorithm(algorithm, "Crypto.digestString");
if (typeof data !== "string") {
throw new TypeError("Crypto.digestString: data must be a string");
}
const encoding = options?.encoding ?? "hex";
if (encoding !== "hex" && encoding !== "base64") {
throw new Error(`Crypto.digestString: encoding must be 'hex' or 'base64'`);
}
const bytes = utf8Encode(data);
const hashed = new Uint8Array(await source(algorithm, bytes.buffer, 0, bytes.length));
return encoding === "base64" ? bytesToBase64(hashed) : bytesToHex(hashed);
}
return {
digest,
digestString
};
}
export { DIGEST_ALGORITHMS, assertDigestAlgorithm, createDigestApi };
//# sourceMappingURL=digest-api.mjs.map