UNPKG

hscrypt

Version:

Encrypt Javascript bundles (at build time), inject+decrypt them into pages later (in the browser)

36 lines 1.98 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.encrypt = void 0; const crypto_js_1 = __importDefault(require("crypto-js")); const crypto_1 = require("./crypto"); const utils_1 = require("./utils"); const ts_chacha20_1 = require("ts-chacha20"); function encrypt({ source, pswd, iterations, }) { iterations = iterations || utils_1.DEFAULT_ITERATIONS; const salt = crypto_js_1.default.lib.WordArray.random(utils_1.SALT_LENGTH); const saltBuf = (0, crypto_1.toUint8Array)(salt); console.time('PBKDF2'); const decryptionKey = (0, crypto_1.toUint8Array)(crypto_js_1.default.PBKDF2(pswd, salt, { hasher: crypto_js_1.default.algo.SHA512, keySize: utils_1.DECRYPTION_KEY_LENGTH / 4, iterations })); console.timeEnd('PBKDF2'); const nonce = (0, crypto_1.toUint8Array)(crypto_js_1.default.lib.WordArray.random(utils_1.NONCE_LENGTH)); console.log(`salt: ${(0, utils_1.toHexString)(saltBuf)}`); console.log(`nonce: ${(0, utils_1.toHexString)(nonce)}`); console.log(`decryptionKey: ${(0, utils_1.toHexString)(decryptionKey)}`); console.log(`iterations: ${iterations}`); const encoder = new ts_chacha20_1.Chacha20(decryptionKey, nonce); const sourceArray = typeof source === 'string' ? new TextEncoder().encode(source) : source; const prefixedSourceArray = new Uint8Array([...utils_1.SOURCE_PREFIX_ARRAY, ...sourceArray]); console.time('ChaCha20'); const ciphertext = encoder.encrypt(prefixedSourceArray); console.timeEnd('ChaCha20'); const encrypted = new Uint8Array(saltBuf.length + nonce.length + ciphertext.length); encrypted.set(saltBuf, 0); encrypted.set(nonce, saltBuf.length); encrypted.set(ciphertext, saltBuf.length + nonce.length); return encrypted; } exports.encrypt = encrypt; //# sourceMappingURL=encrypt.js.map