It seems that there is a simple way of doing this. There is a package called cryptico
that can do the thing.
First install the package:
npm i cryptico
Example
const cryptico = require('cryptico');
const PassPhrase = "The Moon is a Harsh Mistress.";
// The length of the RSA key, in bits.
const Bits = 1024;
const RSAkey = cryptico.generateRSAKey(PassPhrase, Bits);
const PublicKeyString = cryptico.publicKeyString(RSAkey);
A better and complete example can be found here
Update
So, if you need an ASYMMETRIC
encryption (As I know that works with a pair of keys which are called publickey
and privatekey
) you can simply use a pure Node.js
implementation.
Example
const { generateKeyPairSync, publicEncrypt, privateDecrypt } = require('crypto');
const PassPhrase = "The Moon is a Harsh Mistress.";
const Bits = 1024;
const encryptWithRSA = (input, publickey) => {
const buffer = Buffer.from(input, 'utf-8');
const encrypted = publicEncrypt(publicKey, buffer);
return encrypted.toString("base64");
}
const decryptWithRSA = function (input, privatekey) {
const buffer = Buffer.from(input, 'base64');
const decrypted = privateDecrypt(
{
key: privatekey,
passphrase: PassPhrase,
},
buffer,
)
return decrypted.toString("utf8");
};
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
modulusLength: Bits,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: PassPhrase
}
});
const encrypted = encryptWithRSA('yes i know', publicKey)
console.log(encrypted);
console.log(decryptWithRSA(encrypted, privateKey));
Output (The encrypted
value is random as you know)
t3Gw+PlKn84gx2wkj99we345C6ZjIElpgDkzXjio2aWRwI28qTMev14H7o219P6Lw9STGnfK4FgTYO/cvLGlzplqRv6X5AgrstwsGQN88wmKHe5+6cxlpzPFNPWLUqtAvsIOPZe+ghaRGCkOT2ETUp4PiqwOTJ2EtmyVqQHt+f4=
yes i know