by Anish
Posted on Tuesday september 25, 2018
This sample chapter extracted from the book, Cryptography for JavaScript Developers.
In this example we are going to produce the digital signature of the message by using pbkdf2 key derivation function, and then sign the message from the derived key using HMAC, then we are going to verify the message
This is the web cryptography api example of producing digital signature of the message
The first step is to derive the key from the user supplied password,
window.crypto.subtle.importKey(
'raw',
passphraseKey,
{name: 'PBKDF2'},
false,
['deriveBits', 'deriveKey']
).then(function(key) {
return window.crypto.subtle.deriveKey(
{ "name": 'PBKDF2',
"salt": saltBuffer,
"iterations": iterations,
"hash": 'SHA-256'
},
key,
{ "name": 'HMAC', hash: {name: "SHA-256"} },
true,
[ "sign","verify"]
)
}).then(function (webKey) {
publicKey=webKey
Once the key is derived, now we are signing the message, using this derived key
window.crypto.subtle.sign(
{
name: "HMAC"
},
webKey,
asciiToUint8Array(plainText) //ArrayBuffer of data we want to sign
)
.then(function(signature){
document.getElementById("signature").value= bytesToHexString(signature)
})
.catch(function(err){
console.error(err);
});
return crypto.subtle.exportKey("raw", webKey);
}).then(function (buffer) {
document.getElementById("key").value= bytesToHexString(buffer);
document.getElementById("salt").value= bytesToHexString(saltBuffer);
});
Signature Verification To verify the signature of the message, pass the pbdkf2 crypto key,signature and the plain text message
window.crypto.subtle.verify({
name: "HMAC",
},
publicKey,
hexStringToUint8Array(signature),
asciiToUint8Array(plainText)
)
.then(function(decrypted) {
alert("Verified " + decrypted);
})
.catch(function(err) {
console.error(err);
});
Thanku for reading !!! Give a Share for Support
Instead of directly asking for donations, I'm thrilled to offer you all nine of my books for just $9 on leanpub By grabbing this bundle you not only help cover my coffee, beer, and Amazon bills but also play a crucial role in advancing and refining this project. Your contribution is indispensable, and I'm genuinely grateful for your involvement in this journey!
Any private key value that you enter or we generate is not stored on this site, this tool is provided via an HTTPS URL to ensure that private keys cannot be stolen, for extra security run this software on your network, no cloud dependency