by Anish
Posted on Monday september 17, 2018
This sample chapter extracted from the book, Cryptography for JavaScript Developers.
Here's an example showing how to use deriveKey() to create a Secure Remote Password (also known as Proof of Secret) from a user's password using pbkdf2 algorithm
function generateKey(password,iterations) {
// salt should be Uint8Array or ArrayBuffer
var saltBuffer = crypto.getRandomValues(new Uint8Array(8));
var encoder = new TextEncoder('utf-8');
var passphraseKey = encoder.encode("password");
// You should firstly import your passphrase Uint8array into a CryptoKey
window.crypto.subtle.importKey(
'raw',
passphraseKey,
{name: 'PBKDF2'},
false,
['deriveBits', 'deriveKey']
).then(function(key) {
return window.crypto.subtle.deriveKey(
{ "name": 'PBKDF2',
"salt": saltBuffer,
// don't get too ambitious, or at least remember
// that low-power phones will access your app
"iterations": iterations,
"hash": 'SHA-256'
},
key,
// Note: for this demo we don't actually need a cipher suite,
// but the api requires that it must be specified.
// For AES the length required to be 128 or 256 bits (not bytes)
{ "name": 'AES-CBC', "length": 256 },
// Whether or not the key is extractable (less secure) or not (more secure)
// when false, the key can only be passed as a web crypto object, not inspected
true,
// this web crypto object will only be allowed for these functions
[ "encrypt", "decrypt" ]
)
}).then(function (webKey) {
return crypto.subtle.exportKey("raw", webKey);
}).then(function (buffer) {
document.getElementById("key").value= bytesToHexString(buffer);
document.getElementById("salt").value= bytesToHexString(saltBuffer);
});
}
Thanku for reading !!! Give a Share for Support
Asking for donation sound bad to me, so i'm raising fund from by offering all my Nine book for just $9