UNPKG

@ayonli/jsext

Version:

A JavaScript extension package for building strong and modern applications.

99 lines (94 loc) 3.17 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var bytes = require('./bytes.js'); var env = require('./env.js'); var hash_web = require('./hash/web.js'); /** * Simplified hash functions for various data types, based on the Web Crypto API * and `crypto` package in Node.js. * @module */ async function nodeHash(algorithm, data, encoding = undefined) { const crypto = await import('node:crypto'); const bytes = await hash_web.toBytes(data); const hash = crypto.createHash(algorithm); hash.update(bytes); if (encoding) { return hash.digest(encoding); } else { const result = hash.digest(); // Truncate the buffer to the actual byte length so it's consistent with the web API. return result.buffer.slice(result.byteOffset, result.byteOffset + result.byteLength); } } async function sha1(data, encoding = undefined) { if (typeof crypto === "object") { return encoding ? hash_web.sha1(data, encoding) : hash_web.sha1(data); } else if (env.isDeno || env.isNodeLike) { return nodeHash("sha1", data, encoding); } else { throw new Error("Unsupported runtime"); } } async function sha256(data, encoding = undefined) { if (typeof crypto === "object") { return encoding ? hash_web.sha256(data, encoding) : hash_web.sha256(data); } else if (env.isDeno || env.isNodeLike) { return nodeHash("sha256", data, encoding); } else { throw new Error("Unsupported runtime"); } } async function sha512(data, encoding = undefined) { if (typeof crypto === "object") { return encoding ? hash_web.sha512(data, encoding) : hash_web.sha512(data); } else if (env.isDeno || env.isNodeLike) { return nodeHash("sha512", data, encoding); } else { throw new Error("Unsupported runtime"); } } async function md5(data, encoding = undefined) { if (env.isDeno || env.isNodeLike) { return nodeHash("md5", data, encoding); } else { throw new Error("Unsupported runtime"); } } async function hmac(algorithm, key, data, encoding = undefined) { if (typeof crypto === "object") { return encoding ? hash_web.hmac(algorithm, key, data, encoding) : hash_web.hmac(algorithm, key, data); } else if (env.isDeno || env.isNodeLike) { const crypto = await import('node:crypto'); const binary = await hash_web.toBytes(data); const hash = crypto.createHmac(algorithm, bytes.default(key)); hash.update(binary); if (encoding) { return hash.digest(encoding); } else { const result = hash.digest(); // Truncate the buffer to the actual byte length so it's consistent with the web API. return result.buffer.slice(result.byteOffset, result.byteOffset + result.byteLength); } } else { throw new Error("Unsupported runtime"); } } exports.default = hash_web.hash; exports.hmac = hmac; exports.md5 = md5; exports.sha1 = sha1; exports.sha256 = sha256; exports.sha512 = sha512; //# sourceMappingURL=hash.js.map