UNPKG

@unvision/jose

Version:

Implementation of the RFCs of the JOSE Working Group.

64 lines 2.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.JsonWebEncryptionContentEncryptionAlgorithm = void 0; const crypto_1 = require("crypto"); const util_1 = require("util"); const invalid_jsonwebencryption_exception_1 = require("../../../exceptions/invalid-jsonwebencryption.exception"); const randomBytesAsync = (0, util_1.promisify)(crypto_1.randomBytes); /** * Abstract Base Class for the JSON Web Encryption Content Encryption Algorithms. * * All JSON Web Encryption Content Encryption Algorithms **MUST** extend this base class and implement its abstract methods. * * @see https://www.rfc-editor.org/rfc/rfc7518.html#section-5 */ class JsonWebEncryptionContentEncryptionAlgorithm { /** * Instantiates a new JSON Web Encryption Content Encryption Algorithm to Encrypt and Decrypt a Plaintext. * * @param algorithm Name of the JSON Web Encryption Content Encryption Algorithm. * @param cekSize Size of the Content Encryption Key in bits. * @param ivSize Size of the Initialization Vector in bits. */ constructor(algorithm, cekSize, ivSize) { this.algorithm = algorithm; this.cekSize = cekSize; this.ivSize = ivSize; } /** * Generates a new Content Encryption Key. */ async generateContentEncryptionKey() { return await randomBytesAsync(Math.floor(this.cekSize / 8)); } /** * Generates a new Initialization Vector. */ async generateInitializationVector() { return await randomBytesAsync(Math.floor(this.ivSize / 8)); } /** * 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_jsonwebencryption_exception_1.InvalidJsonWebEncryptionException(); } } /** * 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_jsonwebencryption_exception_1.InvalidJsonWebEncryptionException(); } } } exports.JsonWebEncryptionContentEncryptionAlgorithm = JsonWebEncryptionContentEncryptionAlgorithm; //# sourceMappingURL=jsonwebencryption-content-encryption.algorithm.js.map