Last active
January 6, 2023 14:06
-
-
Save rawinng/f7ba83a101afc0716bb74497ab324d85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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