aead-stream
Version:
Authenticated encryption on arbitrary large files
30 lines (29 loc) • 1.17 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.encrypt = void 0;
const crypto_1 = require("crypto");
const chunkify_1 = require("./chunkify");
const options_1 = require("./options");
async function* encrypt(key, plaintext, options = options_1.defaultOptions) {
const { algorithm, authTagLength, nonceLength, associatedData } = options;
const chunkSize = options.chunkSize - nonceLength - authTagLength;
let chunkIndex = 0;
for await (const chunk of (0, chunkify_1.chunkify)(chunkSize, plaintext)) {
const nonce = (0, crypto_1.randomBytes)(nonceLength);
let cipher = (0, crypto_1.createCipheriv)(algorithm, key, nonce, {
authTagLength,
});
let aad = Buffer.from([chunkIndex++]);
if (associatedData) {
aad = Buffer.concat([aad, associatedData]);
}
cipher.setAAD(aad, {
plaintextLength: chunk.length,
});
const ciphertext = cipher.update(chunk);
cipher.final();
const authTag = cipher.getAuthTag();
yield Buffer.concat([nonce, ciphertext, authTag]);
}
}
exports.encrypt = encrypt;