How to Encrypt / Decrypt strings with RSA in Node.JS

Interesting things that go through my mind during lock-down haha!

const crypto = require('crypto');

const PASSPHRASE = 'I had learned that some things are best kept secret.';

const KEY_PAIR_OPTIONS = {

    modulusLength: 2048,
    publicKeyEncoding: {
        type: 'spki',
        format: 'pem'
    },
    privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem',
        cipher: 'aes-256-cbc',
        passphrase: PASSPHRASE
    }

};

const KEY_PAIR = crypto.generateKeyPairSync('rsa', KEY_PAIR_OPTIONS);

const RSA_PRK = KEY_PAIR.privateKey;
const RSA_PUK = KEY_PAIR.publicKey;

console.log("\n>>> Private Key: \n\n" + RSA_PRK);
console.log(">>> Public Key: \n\n" + RSA_PUK);

var message = "This message will be encrypted with my public key so that only me can decrypt it with my private key.";
console.log(">>> Original message: \n\n" + message);

var encMsg = crypto.publicEncrypt(RSA_PUK, Buffer.from(message));
var encMsgB64 = encMsg.toString('base64');
console.log("\n>>> Encrypted message (base 64): \n\n" + encMsgB64);

const PRK_OBJ = {
    key: RSA_PRK,
    passphrase: PASSPHRASE
};

var decMsg = crypto.privateDecrypt(PRK_OBJ, Buffer.from(encMsgB64, 'base64'));
var decMsgUtf8 = decMsg.toString('utf8');
console.log("\n>>> Dencrypted message: \n\n" + decMsgUtf8);

if (message === decMsgUtf8) {
    console.log("\n>>> Match: TRUE!");
} else {
    console.log("\n>>> Match: FALSE!");
}
Your console output should look similar to this:
B:\Code\NodeJS> node RSA_Encrypt_Decrypt.js

>>> Private Key:

-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIFLTBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQIt/Vq80bA27sCAggA
MAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBCaRitlsLzyOF4V2u2Ev87QBIIE
0EgI83FGo2TFrDl5LL+xmOtl1UuYwZ/2udcDtRAjIVLbGEbnopbWKMR0y2fDq9Yy
9zYreTIABcwBWjm7reVYmrq9VTJy9KJvGZz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UFUSnY0nalyL9L
gihHEGcKG3Xx8JBZNGpMeaBnRBIi7nmoaxZhj+kTOgnf2YtfP3zAWKpkpOpBfm7t
oGkIP4yuU6bvEZXTqUCelpORNhhbRecHJKvX+pv0zvWJVpSahxMEgDwmduAsY+Xw
Pe/Q+tYlEKYy/lQGuzUhO4ZKfeqq4/EaYmzjkNcU9monwpMG8hA/fpnIF9JyORjO
LA631K0o3p9Vm2pwNZJy7ZlB2r/VBRNbLfVXbFfQ674yI6SLlPn8NXMvOamhUEEh
1TWVWniwcusel8h34Ujrtw4hpWn7AeeqkcvwhcxGCuJJL+oidE1duCOwPmPvfESz
ARPzPA/NIo7AbMyzQGnYGuwFLyqozT33mtX9fYEuJGbsK+Gp6VNxdsviUMqmPBuC
Ck5cmirjne7d6FyqsHeiuH1My/QPWGguLOWzAx1KJtV+iqd8zfgfMLikB3umH+Y2
44S5xVdm6KHVpjFES+TWQEst7km72aSvekHD3ue2EOtI
-----END ENCRYPTED PRIVATE KEY-----

>>> Public Key:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyOCGGFkEhPE1nFm/6QTX
PlgCCmlmNacyO/Lxl36Bes/W1sdayPYpQwjNcUCYqGWvpI2cWe/YEPFl3QsrqMjf
5qZq1RPTpNyNBxVqsdqlIA4K5FVDHFGuLnTJ1dpSejZQqbCDW44LvCeIRPytQy03
ajxFERJTuLqiSEO5FF+TLJogEi2euBdPZjBBdsJNiUE36tRNlEY05fjyqQsgh+1R
0SkWVsQpwFpu+SwY0Z6PfEeqLj/oqZI0jNwOce0bbZoGmdkk06BYhZvvywi9hahx
UkYDcZ9P5eow1ChOO7ys/OoPlnM76iad9PXFJzMc7oPcH51m8fCenmQE63jtDgut
WwIDAQAB
-----END PUBLIC KEY-----

>>> Original message:

This message will be encrypted with my public key so that only me can decrypt it with my private key.

>>> Encrypted message (base 64):

kmXPtaPhWSt8l6JDATlTMxiemsBeqAhgj8Ek44GTU7T2GWyB+VlvorA86Ghe8mdM49zm19JNHBXqrcHzggvdfNXyQxiuZBlHALlxJOn3nMIKN89+S0jexSbfk2n4/eqAggU4O8Ms8gedTuPzxOeX/qZ0JO/hXh6FTIi8zesL55eU9YX9CdaqBJj7wyB3ooWcC2gv6ibpetLi3u9wlXRStO7Kdof3/0IXYa8n64t0kZ0eH23domJ+J6GaQh2p6yoeN7L9kzuvnKL5OABdStsJ5uCBQ8UASKQ6+6AVg/bD+DlwIJE7tS7GJsrUK+7+2aYHMq9Eiu4Wm8A9tFPYlX+oXg==

>>> Dencrypted message:

This message will be encrypted with my public key so that only me can decrypt it with my private key.

>>> Match: TRUE!

B:\Code\NodeJS>
You can see a web application using this algorithm here.

 

Sources:

Leave a Comment

Your email address will not be published. Required fields are marked *