by Anish
Posted on Friday september 21, 2018
This sample chapter extracted from the book, Cryptography for JavaScript Developers.
The Web crypto api RSA-OAEP algorithm identifier is used to perform encryption and decryption ordering to the RSAES-OAEP algorithm , using the SHA hash functions defined in this specification and using the mask generation function MGF1.
This is the web cryptography api example of performing rsa oaep encryption decryption
Generate the RSA-OAEP 2048 bit Keys using SHA-256 Algorithms
window.crypto.subtle.generateKey({
name: "RSA-OAEP",
modulusLength: 2048, //can be 1024, 2048, or 4096
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {
name: "SHA-256"
}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
},
true, //whether the key is extractable (i.e. can be used in exportKey)
["encrypt", "decrypt"] //must be ["encrypt", "decrypt"] or ["wrapKey", "unwrapKey"]
)
Sample Export keys to display the RSA public private key in JWK format (You can skip this step) This is for demo purpose, which i showed in UI.
window.crypto.subtle.exportKey("jwk", key.publicKey).then(
function(keydata) {
publicKeyhold = keydata;
publicKeyJson = JSON.stringify(publicKeyhold);
document.getElementById("rsapublic").value = publicKeyJson;
}
);
window.crypto.subtle.exportKey("jwk", key.privateKey).then(
function(keydata) {
privateKeyhold = keydata;
privateKeyJson = JSON.stringify(privateKeyhold);
document.getElementById("rsaprivate").value = privateKeyJson;
}
);
RSA-OAEP Encryption Example
window.crypto.subtle.encrypt({
name: "RSA-OAEP",
iv: iv,
},
publicKey, //from generateKey or importKey above
asciiToUint8Array(plainText) //ArrayBuffer of data you want to encrypt
)
.then(function(encrypted) {
//returns an ArrayBuffer containing the encrypted data
document.getElementById("cipherText").value = bytesToHexString(encrypted);
document.getElementById("salt").value = bytesToHexString(iv);
})
.catch(function(err) {
console.error(err);
});
RSA-OAEP decryption Example
var cipherText = document.getElementById("cipherText").value;
window.crypto.subtle.decrypt({
name: "RSA-OAEP",
iv: iv
},
privateKey, //from generateKey or importKey above
hexStringToUint8Array(cipherText) //ArrayBuffer of the data
)
.then(function(decrypted) {
alert(bytesToASCIIString(decrypted));
})
.catch(function(err) {
console.error(err);
});
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