nodejs rsa encryption code example
Example 1: rsa encryption js
npm install crypto
const crypto = require("crypto")
const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
})
const data = "my secret data"
const encryptedData = crypto.publicEncrypt(
{
key: publicKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: "sha512",
},
Buffer.from(data)
)
console.log("encypted data: ", encryptedData.toString("base64"))
const decryptedData = crypto.privateDecrypt(
{
key: privateKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: "sha512",
},
encryptedData
)
console.log("decrypted data: ", decryptedData.toString())
const verifiableData = "this need to be verified"
const signature = crypto.sign("sha512", Buffer.from(verifiableData), {
key: privateKey,
padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
})
console.log(signature.toString("base64"))
const isVerified = crypto.verify(
"sha512",
Buffer.from(verifiableData),
{
key: publicKey,
padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
},
signature
)
console.log("signature verified: ", isVerified)
Example 2: Encryption RSA, JavaScript
<script type="text/javascript">
$(function () {
$(".change-key-size").each(function (index, value) {
var el = $(value);
var keySize = el.attr('data-value');
el.click(function (e) {
var button = $('#key-size');
button.attr('data-value', keySize);
button.html(keySize + ' bit <span class="caret"></span>');
e.preventDefault();
});
});
$('#execute').click(function () {
var crypt = new JSEncrypt();
crypt.setPrivateKey($('#privkey').val());
var pubkey = $('#pubkey').val();
if (!pubkey) {
$('#pubkey').val(crypt.getPublicKey());
}
var input = $('#input').val();
var crypted = $('#crypted').val();
if (input) {
$('#crypted').val(crypt.encrypt(input));
$('#input').val('');
}
else if (crypted) {
var decrypted = crypt.decrypt(crypted);
if (!decrypted)
decrypted = 'This is a test!';
$('#input').val(decrypted);
$('#crypted').val('');
}
});
var generateKeys = function () {
var sKeySize = $('#key-size').attr('data-value');
var keySize = parseInt(sKeySize);
var crypt = new JSEncrypt({ default_key_size: keySize });
var async = $('#async-ck').is(':checked');
var dt = new Date();
var time = -(dt.getTime());
if (async) {
$('#time-report').text('.');
var load = setInterval(function () {
var text = $('#time-report').text();
$('#time-report').text(text + '.');
}, 500);
crypt.getKey(function () {
clearInterval(load);
dt = new Date();
time += (dt.getTime());
$('#time-report').text('Generated in ' + time + ' ms');
$('#privkey').val(crypt.getPrivateKey());
$('#pubkey').val(crypt.getPublicKey());
});
return;
}
crypt.getKey();
dt = new Date();
time += (dt.getTime());
$('#time-report').text('Generated in ' + time + ' ms');
$('#privkey').val(crypt.getPrivateKey());
$('#pubkey').val(crypt.getPublicKey());
};
$('#generate').click(generateKeys);
generateKeys();
});
</script>