UNPKG

1.43 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.decryptRandomIVBuffer = exports.encryptRandomIVBuffer = void 0;
4const crypto = require("crypto");
5const hash_util_1 = require("./hash.util");
6// const randomBytes = promisify(crypto.randomBytes)
7function aes256Key(secretKeyBase64) {
8 // md5 to match aes-256 key length of 32 bytes
9 return (0, hash_util_1.md5)(Buffer.from(secretKeyBase64, 'base64'));
10}
11function encryptRandomIVBuffer(input, secretKeyBase64, algorithm = 'aes-256-cbc') {
12 const key = aes256Key(secretKeyBase64);
13 // Random iv to achieve non-deterministic encryption (but deterministic decryption)
14 // const iv = await randomBytes(16)
15 const iv = crypto.randomBytes(16); // use sync method here for speed
16 const cipher = crypto.createCipheriv(algorithm, key, iv);
17 return Buffer.concat([iv, cipher.update(input), cipher.final()]);
18}
19exports.encryptRandomIVBuffer = encryptRandomIVBuffer;
20function decryptRandomIVBuffer(input, secretKeyBase64, algorithm = 'aes-256-cbc') {
21 const key = aes256Key(secretKeyBase64);
22 // iv is first 16 bytes of encrypted buffer, the rest is payload
23 const iv = input.slice(0, 16);
24 const payload = input.slice(16);
25 const decipher = crypto.createDecipheriv(algorithm, key, iv);
26 return Buffer.concat([decipher.update(payload), decipher.final()]);
27}
28exports.decryptRandomIVBuffer = decryptRandomIVBuffer;