@nasriya/cachify
Version:
A lightweight, extensible in-memory caching library for storing anything, with built-in TTL and customizable cache types.
56 lines (55 loc) • 1.62 kB
JavaScript
import crypto from 'crypto';
import helpers from "../helpers.js";
import { Transform } from "stream";
class EncryptStream extends Transform {
#_key;
#_chunkProcessor = helpers.createChunkProcessor();
#_iv = null;
#_cipher;
#_handler = null;
#ivSent = false;
constructor(key) {
super();
if (key.length !== 32) {
throw new Error('Key must be 32 bytes (256 bits) long');
}
this.#_key = key;
this.#_iv = crypto.randomBytes(16); // 128-bit IV for AES-256-CBC
this.#_cipher = crypto.createCipheriv('aes-256-cbc', this.#_key, this.#_iv);
}
#encrypt(data) {
return this.#_cipher.update(data);
}
#setHandler(callback) {
this.#_handler = helpers.createCallbackHandler(callback, this.#encrypt.bind(this));
}
#processChunk(chunk) {
return this.#_chunkProcessor(chunk, this.#_handler);
}
_transform(chunk, encoding, callback) {
this.#setHandler(callback);
try {
if (!this.#ivSent) {
// Push the IV first so decryptor can read it
this.push(this.#_iv);
this.#ivSent = true;
}
this.#processChunk(chunk);
}
catch (err) {
callback(err);
}
}
_flush(callback) {
this.#setHandler(callback);
try {
this.#_chunkProcessor.flush(this.#_handler);
const final = this.#_cipher.final();
this.push(final);
}
catch (err) {
callback(err);
}
}
}
export default EncryptStream;