@guarani/jose
Version:
Implementation of the RFCs of the JOSE Working Group.
75 lines (74 loc) • 3.11 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.HS512 = exports.HS384 = exports.HS256 = void 0;
const crypto_1 = require("crypto");
const invalid_json_web_key_exception_1 = require("../../exceptions/invalid-json-web-key.exception");
const invalid_json_web_signature_exception_1 = require("../../exceptions/invalid-json-web-signature.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 the Messages.
*
* @param hash Hash Algorithm used to Sign and Verify the Messages.
* @param algorithm Name of the JSON Web Signature Algorithm.
* @param keySize Size of the Secret accepted by the JSON Web Signature HMAC Algorithm.
*/
constructor(hash, algorithm, keySize) {
super(hash, algorithm, '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 = Reflect.get(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_json_web_signature_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_json_web_key_exception_1.InvalidJsonWebKeyException(`The size of the OctKey Secret must be at least ${this.keySize} bytes.`);
}
}
}
/**
* HMAC using SHA-256.
*/
exports.HS256 = new HmacAlgorithm('SHA256', 'HS256', 32);
/**
* HMAC using SHA-384.
*/
exports.HS384 = new HmacAlgorithm('SHA384', 'HS384', 48);
/**
* HMAC using SHA-512.
*/
exports.HS512 = new HmacAlgorithm('SHA512', 'HS512', 64);