我已经使用RSA算法使用公钥加密数据,并将私钥传输到客户端进行解密,但这并没有发生。我已经尝试了很多方法来做,但它没有完成,我已经创建了一个回购。Link是:
Repo Link is here
const crypto = require('crypto');
let { privateKey, publicKey } = encryption.generate_key();
console.log('Private Key:', privateKey);
console.log('Public Key:', publicKey);
const plaintext = 'This is the message to be encrypted';
console.log('Plaintext:', plaintext);
const encrypted = encryption.enc(plaintext, publicKey);
console.log('Encrypted:', encrypted);
encryption.dec(encrypted, privateKey);
res.render('final',{privateKey : privateKey,encrypted : encrypted});
encryption.generate_key()函数
function generate_key() {
const keys = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
});
const { privateKey, publicKey } = keys;
return { privateKey, publicKey };
}
function enc(plainText, publicKey) {
const buffer = Buffer.from(plainText, 'utf-8');
const encrypted = crypto.publicEncrypt(
{ key: publicKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING },
buffer
);
return encrypted.toString('base64');
}
function dec(cipherText, privateKey) {
const buffer = Buffer.from(cipherText, 'base64');
const decrypted = crypto.privateDecrypt(
{ key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING },
buffer
);
return decrypted.toString('utf-8');
}
客户端代码(ejs)
<script src="/jsencrypt.min.js"></script>
<script>
let privateKey = `<%= privateKey %>`;
let encrypted = `<%= encrypted %>`;
var crypt = new JSEncrypt();
crypt.setPrivateKey(privateKey);
var decrypted = crypt.decrypt(encrypted);
console.log(decrypted);
console.log(privateKey,encrypted);
</script>
1条答案
按热度按时间btqmn9zl1#
使用此方法👇: