UNPKG

@unvision/jose

Version:

Implementation of the RFCs of the JOSE Working Group.

74 lines 2.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HS512 = exports.HS384 = exports.HS256 = void 0; const crypto_1 = require("crypto"); const invalid_jsonwebkey_exception_1 = require("../../exceptions/invalid-jsonwebkey.exception"); const invalid_jsonwebsignature_exception_1 = require("../../exceptions/invalid-jsonwebsignature.exception"); const jsonwebsignature_algorithm_1 = require("./jsonwebsignature.algorithm"); /** * Implementation of the JSON Web Signature HMAC Algorithm. */ class HmacAlgorithm extends jsonwebsignature_algorithm_1.JsonWebSignatureAlgorithm { /** * Instantiates a new JSON Web Signature HMAC Algorithm to Sign and Verify Messages. * * @param keySize Size of the Secret accepted by the JSON Web Signature HMAC Algorithm. */ constructor(keySize) { const bitSize = keySize << 3; super(`HS${bitSize}`, `SHA${bitSize}`, 'oct'); this.keySize = keySize; } /** * Signs a Message with the provided JSON Web Key. * * @param message Message to be Signed. * @param key JSON Web Key used to Sign the provided Message. * @returns Resulting Signature of the provided Message. */ async sign(message, key) { this.validateJsonWebKey(key); const cryptoKey = key['cryptoKey']; const signature = (0, crypto_1.createHmac)(this.hash, cryptoKey).update(message).digest(); return signature; } /** * Checks if the provided Signature matches the provided Message based on the provide JSON Web Key. * * @param signature Signature to be matched against the provided Message. * @param message Message to be matched against the provided Signature. * @param key JSON Web Key used to verify the Signature and Message. */ async verify(signature, message, key) { this.validateJsonWebKey(key); const calculatedSignature = await this.sign(message, key); if (!(0, crypto_1.timingSafeEqual)(signature, calculatedSignature)) { throw new invalid_jsonwebsignature_exception_1.InvalidJsonWebSignatureException(); } } /** * Checks if the provided JSON Web Key can be used by the JSON Web Signature HMAC Algorithm. * * @param key JSON Web Key to be checked. * @throws {InvalidJsonWebKeyException} The provided JSON Web Key is invalid. */ validateJsonWebKey(key) { super.validateJsonWebKey(key); if (Buffer.from(key.k, 'base64url').length < this.keySize) { throw new invalid_jsonwebkey_exception_1.InvalidJsonWebKeyException(`The size of the OctKey Secret must be at least ${this.keySize} bytes.`); } } } /** * HMAC using SHA-256. */ exports.HS256 = new HmacAlgorithm(32); /** * HMAC using SHA-384. */ exports.HS384 = new HmacAlgorithm(48); /** * HMAC using SHA-512. */ exports.HS512 = new HmacAlgorithm(64); //# sourceMappingURL=hmac.algorithm.js.map