Skip to content

Instantly share code, notes, and snippets.

@perry-mitchell
Last active August 20, 2019 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perry-mitchell/a495ee00ac8055dea51102a486b11462 to your computer and use it in GitHub Desktop.
Save perry-mitchell/a495ee00ac8055dea51102a486b11462 to your computer and use it in GitHub Desktop.
Key derivation in NodeJS
const { pbkdf2: deriveKey } = require("pbkdf2");
const HMAC_KEY_SIZE = 32;
const PASSWORD_KEY_SIZE = 32;
function pbkdf2(password, salt, rounds, bits) {
return new Promise((resolve, reject) => {
deriveKey(password, salt, rounds, bits / 8, "sha256", (err, key) => {
if (err) {
return reject(err);
}
return resolve(key);
});
});
}
function deriveFromPassword(password, salt, rounds) {
if (!password) {
return Promise.reject(new Error("Failed deriving key: Password must be provided"));
}
if (!salt) {
return Promise.reject(new Error("Failed deriving key: Salt must be provided"));
}
if (!rounds || rounds <= 0 || typeof rounds !== "number") {
return Promise.reject(new Error("Failed deriving key: Rounds must be greater than 0"));
}
const bits = (PASSWORD_KEY_SIZE + HMAC_KEY_SIZE) * 8;
return pbkdf2(password, salt, rounds, bits)
.then(derivedKeyData => derivedKeyData.toString("hex"))
.then(function(derivedKeyHex) {
const dkhLength = derivedKeyHex.length;
const keyBuffer = new Buffer(derivedKeyHex.substr(0, dkhLength / 2), "hex");
const output = {
salt: salt,
key: keyBuffer,
rounds: rounds,
hmac: new Buffer(derivedKeyHex.substr(dkhLength / 2, dkhLength / 2), "hex")
};
return output;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment