Here is an example of how you can use the crypto module in Node.js to generate RSA key pairs and use them to encrypt and decrypt data:
const crypto = require('crypto');
// Generate a new RSA key pair
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: 'secret'
}
});
// Encrypt the data using the public key
const data = 'Hello, World!';
const encrypted = crypto.publicEncrypt(publicKey, Buffer.from(data));
// Decrypt the data using the private key
const decrypted = crypto.privateDecrypt(privateKey, encrypted);
console.log(decrypted.toString()); // 'Hello, World!'
This example generates an RSA key pair with a modulus length of 4096 bits, and uses the aes-256-cbc algorithm to encrypt the private key. The public key is encoded in the SPKI format and the private key is encoded in the PKCS8 format, both using the PEM encoding type.
The publicEncrypt() method is used to encrypt the data using the public key, and the privateDecrypt() method is used to decrypt it using the private key.
I hope this helps!
.jpg)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.