From 04bcd9547b7508eba970c325eef5f9bbb1a64d88 Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Thu, 14 Jan 2021 10:50:01 +0100 Subject: [PATCH] refactor: use native node hkdf when available --- lib/hkdf.js | 38 ++++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/lib/hkdf.js b/lib/hkdf.js index 3bce27a3..5a1e96ac 100644 --- a/lib/hkdf.js +++ b/lib/hkdf.js @@ -1,9 +1,9 @@ -const hkdf = require('futoin-hkdf'); +const crypto = require('crypto'); const BYTE_LENGTH = 32; const ENCRYPTION_INFO = 'JWE CEK'; const SIGNING_INFO = 'JWS Cookie Signing'; -const options = { hash: 'SHA-256' }; +const DIGEST = 'sha256'; /** * @@ -13,7 +13,33 @@ const options = { hash: 'SHA-256' }; * @see https://tools.ietf.org/html/rfc5869 * */ -module.exports.encryption = (secret) => - hkdf(secret, BYTE_LENGTH, { info: ENCRYPTION_INFO, ...options }); -module.exports.signing = (secret) => - hkdf(secret, BYTE_LENGTH, { info: SIGNING_INFO, ...options }); + +if (crypto.hkdfSync) { + // added in v15.0.0 + module.exports.encryption = (secret) => + Buffer.from( + crypto.hkdfSync( + DIGEST, + secret, + Buffer.alloc(0), + ENCRYPTION_INFO, + BYTE_LENGTH + ) + ); + module.exports.signing = (secret) => + Buffer.from( + crypto.hkdfSync( + DIGEST, + secret, + Buffer.alloc(0), + SIGNING_INFO, + BYTE_LENGTH + ) + ); +} else { + const hkdf = require('futoin-hkdf'); + module.exports.encryption = (secret) => + hkdf(secret, BYTE_LENGTH, { info: ENCRYPTION_INFO, hash: DIGEST }); + module.exports.signing = (secret) => + hkdf(secret, BYTE_LENGTH, { info: SIGNING_INFO, hash: DIGEST }); +}