我想在nodejs中加密数据并在javascript中解密。我尝试了很多方法,但每次我都会出现错误格式错误的 utf8 数据

问题描述 投票:0回答:0

我已经使用RSA算法使用公钥加密数据并将私钥传输到客户端进行解密,但它没有发生。我尝试了很多方法,但还没有完成,我创建了一个回购协议。链接是:

回购链接在这里

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>
javascript node.js encryption rsa
© www.soinside.com 2019 - 2024. All rights reserved.