Last active
August 20, 2019 16:27
-
-
Save perry-mitchell/a495ee00ac8055dea51102a486b11462 to your computer and use it in GitHub Desktop.
Key derivation in NodeJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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