@guarani/jose
Version:
Implementation of the RFCs of the JOSE Working Group.
63 lines (62 loc) • 2.73 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsonWebEncryptionContentEncryptionAlgorithm = void 0;
const crypto_1 = require("crypto");
const util_1 = require("util");
const invalid_json_web_encryption_exception_1 = require("../../../exceptions/invalid-json-web-encryption.exception");
const randomBytesAsync = (0, util_1.promisify)(crypto_1.randomBytes);
/**
* Abstract Base Class for {@link https://www.rfc-editor.org/rfc/rfc7518.html#section-5 RFC 7518 Section 5}.
*
* All JSON Web Encryption Content Encryption Algorithms supported by Guarani **MUST** extend this base class
* and implement its abstract methods.
*/
class JsonWebEncryptionContentEncryptionAlgorithm {
/**
* Instantiates a new JSON Web Encryption Content Encryption Algorithm to Encrypt and Decrypt a Plaintext.
*
* @param cekSize Size of the Content Encryption Key in bits.
* @param ivSize Size of the Initialization Vector in bits.
* @param algorithm Name of the JSON Web Encryption Content Encryption Algorithm.
*/
constructor(cekSize, ivSize, algorithm) {
this.cekSize = cekSize;
this.ivSize = ivSize;
this.algorithm = algorithm;
}
/**
* Generates a new Initialization Vector.
*/
async generateInitializationVector() {
return await randomBytesAsync(Math.floor(this.ivSize / 8));
}
/**
* Generates a new Content Encryption Key.
*/
async generateContentEncryptionKey() {
return await randomBytesAsync(Math.floor(this.cekSize / 8));
}
/**
* Checks if the provided Initialization Vector can be used by the JSON Web Encryption Content Encryption Algorithm.
*
* @param iv Initialization Vector to be checked.
* @throws {InvalidJsonWebEncryptionException} The provided Initialization Vector is invalid.
*/
validateInitializationVector(iv) {
if (iv.length * 8 !== this.ivSize) {
throw new invalid_json_web_encryption_exception_1.InvalidJsonWebEncryptionException();
}
}
/**
* Checks if the provided Content Encryption Key can be used by the JSON Web Encryption Content Encryption Algorithm.
*
* @param key Content Encryption Key to be checked.
* @throws {InvalidJsonWebEncryptionException} The provided Content Encryption Key is invalid.
*/
validateContentEncryptionKey(key) {
if (!Buffer.isBuffer(key) || key.length * 8 !== this.cekSize) {
throw new invalid_json_web_encryption_exception_1.InvalidJsonWebEncryptionException('Invalid Content Encryption Key.');
}
}
}
exports.JsonWebEncryptionContentEncryptionAlgorithm = JsonWebEncryptionContentEncryptionAlgorithm;