const crypto = require(
'crypto'
);
const fs = require(
'fs'
);
const path = require(
'path'
);
function
generateKeyFiles() {
const keyPair = crypto.generateKeyPairSync(
'rsa'
, {
modulusLength: 520,
publicKeyEncoding: {
type:
'spki'
,
format:
'pem'
},
privateKeyEncoding: {
type:
'pkcs8'
,
format:
'pem'
,
cipher:
'aes-256-cbc'
,
passphrase:
''
}
});
fs.writeFileSync(
"public_key"
, keyPair.publicKey);
fs.writeFileSync(
"private_key"
, keyPair.privateKey);
}
generateKeyFiles();
let PRIVKEY = fs.readFileSync(path.join(__dirname,
'private_key'
),
'utf8'
);
let PUBKEY = fs.readFileSync(path.join(__dirname,
'public_key'
),
'utf8'
);
myMSG =
"GeeksforGeeks!"
;
console.log(
"Original msg is : "
+ myMSG);
function
privENC_pubDEC(originMSG) {
encmsg = crypto.privateEncrypt(PRIVKEY,
Buffer.from(originMSG,
'utf8'
))
.toString(
'base64'
);
msg = crypto.publicDecrypt(PUBKEY,
Buffer.from(encmsg,
'base64'
));
console.log();
console.log(
"Encrypted with private key: "
+ encmsg);
console.log();
console.log(
"Decrypted with public key: "
+ msg.toString());
}
privENC_pubDEC(myMSG);