我想在nodejs中加密数据并在javascript中解密,我已经尝试了很多方法,但每次我这样做的错误出来畸形utf8数据

9wbgstp7  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(100)

我已经使用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>
btqmn9zl

btqmn9zl1#

使用此方法👇:

var express = require("express");
var app = express();
var body_parser = require("body-parser");
var CryptoJS = require("crypto-js");

// Encryption and decryption keys
var encryptionKey = "myEncryptionKey";
var decryptionKey = "myDecryptionKey";

app.use(body_parser.urlencoded({extended:false}));
app.use(body_parser.json());

app.get("/", (req, res) => {
    let data = "Hello world!"; // data to be encrypted
    let ciphertext = CryptoJS.AES.encrypt(data, encryptionKey).toString();
    let html = `<html>
    <body>
        <p>decryption key => : 'myDecryptionKey'</p>
        <script>
            console.log("Encrypted data: ${ciphertext}");
        </script>
        <form method="post" action="/decrypt">
            <input type="hidden" name="ciphertext" value="${ciphertext}">
            <input type="text" name="decryptionKey" placeholder="Decryption Key">
            <button type="submit">Decrypt</button>
        </form>
    </body>
  </html>`;
    res.status(200).send(html);
});

app.post("/decrypt", (req, res) => {
    let ciphertext = req.body.ciphertext;
    let decryptionKeyServer = req.body.decryptionKey;

    try {
        if (decryptionKeyServer !== decryptionKey) {
            throw new Error("Invalid decryption key");
        }
        let decryptedData = CryptoJS.AES.decrypt(ciphertext, encryptionKey).toString(CryptoJS.enc.Utf8);
        res.status(200).send(`Received ciphertext: ${ciphertext}<br>Decrypted plaintext: ${decryptedData}`);
        console.log(decryptedData)
    } catch (err) {
        res.status(400).send("Error decrypting data. " + err.message);
    }
});

app.listen(3000, () => {
    console.log("Server listening on http://localhost:3000");
});

相关问题