Skip to content

Instantly share code, notes, and snippets.

@rawinng
Last active January 6, 2023 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rawinng/f7ba83a101afc0716bb74497ab324d85 to your computer and use it in GitHub Desktop.
Save rawinng/f7ba83a101afc0716bb74497ab324d85 to your computer and use it in GitHub Desktop.
const forge = require('node-forge');
const { pki, md, util } = forge;
const { rsa } = pki;
function encryptByForge(message, publicKey) {
// const buffer = util.createBuffer(message, "utf8"); // FIX THIS
const buffer = Buffer.from(message, "utf-8");
const encrypted = publicKey.encrypt(buffer, "RSA-OAEP", {
md: md.sha256.create(),
mgf1: {
md: md.sha1.create()
}
});
return util.encode64(encrypted);
};
function decryptByForge(ciphertextReceivedBase64, privateKey) {
const buffer = Buffer.from(ciphertextReceivedBase64, 'base64');
const decrypted = privateKey.decrypt(buffer, "RSA-OAEP", {
md: md.sha256.create(),
mgf1: {
md: md.sha1.create()
}
});
return decrypted.toString('utf-8');
};
const keyPair = rsa.generateKeyPair(2048);
const srcText = "The quick brown fox jumps over the lazy dog";
let encText = encryptByForge(srcText, keyPair.publicKey);
console.log(`enc-text: ${encText}`);
let decText = decryptByForge(encText, keyPair.privateKey);
console.log(`dec-text: ${decText}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment