Skip to content

Commit

Permalink
refactor: use native node hkdf when available (#177)
Browse files Browse the repository at this point in the history
  • Loading branch information
panva authored Jan 14, 2021
1 parent ac45cdd commit 302597c
Showing 1 changed file with 32 additions and 6 deletions.
38 changes: 32 additions & 6 deletions lib/hkdf.js
Original file line number Diff line number Diff line change
@@ -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';

/**
*
Expand All @@ -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 });
}

0 comments on commit 302597c

Please sign in to comment.