@guarani/jose
Version:
Implementation of the RFCs of the JOSE Working Group.
74 lines (73 loc) • 3.02 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.A256GCM = exports.A192GCM = exports.A128GCM = void 0;
const crypto_1 = require("crypto");
const jsonwebencryption_contentencryption_algorithm_1 = require("./jsonwebencryption-contentencryption.algorithm");
/**
* Implementation of the AES-GCM JSON Web Encryption Content Encryption Algorithm.
*/
class AESGCMContentEncryptionAlgorithm extends jsonwebencryption_contentencryption_algorithm_1.JsonWebEncryptionContentEncryptionAlgorithm {
/**
* Instantiates a new AES-GCM JSON Web Encryption Content Encryption to Encrypt and Decrypt a Plaintext.
*
* @param algorithm Name of the JSON Web Encryption Content Encryption Algorithm.
*/
constructor(algorithm) {
const cekSize = Number.parseInt(algorithm.substring(1, 4));
super(cekSize, 96, algorithm);
/**
* Size of the Authentication Tag in bytes.
*/
this.authTagLength = 16;
this.cipherAlgorithm = `aes-${cekSize}-gcm`;
}
/**
* Encrypts the provided Plaintext.
*
* @param plaintext Plaintext to be Cncrypted.
* @param aad Additional Authenticated Data.
* @param iv Initialization Vector.
* @param key Content Encryption Key used to Encrypt the provided Plaintext.
* @returns Resulting Ciphertext and Authentication Tag.
*/
async encrypt(plaintext, aad, iv, key) {
this.validateInitializationVector(iv);
this.validateContentEncryptionKey(key);
const cipher = (0, crypto_1.createCipheriv)(this.cipherAlgorithm, key, iv, { authTagLength: this.authTagLength });
cipher.setAAD(aad);
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
const tag = cipher.getAuthTag();
return { ciphertext, tag };
}
/**
* Decrypts the provided Ciphertext back to its original Plaintext.
*
* @param ciphertext Ciphertext to be Decrypted.
* @param aad Additional Authenticated Data.
* @param iv Initialization Vector.
* @param tag Authentication Tag.
* @param key Content Encryption Key used to Decrypt the provided Ciphertext.
* @returns Resulting Plaintext.
*/
async decrypt(ciphertext, aad, iv, tag, key) {
this.validateInitializationVector(iv);
this.validateContentEncryptionKey(key);
const decipher = (0, crypto_1.createDecipheriv)(this.cipherAlgorithm, key, iv, { authTagLength: this.authTagLength });
decipher.setAAD(aad);
decipher.setAuthTag(tag);
const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
return decrypted;
}
}
/**
* AES GCM using 128-bit key.
*/
exports.A128GCM = new AESGCMContentEncryptionAlgorithm('A128GCM');
/**
* AES GCM using 192-bit key.
*/
exports.A192GCM = new AESGCMContentEncryptionAlgorithm('A192GCM');
/**
* AES GCM using 256-bit key.
*/
exports.A256GCM = new AESGCMContentEncryptionAlgorithm('A256GCM');