gpt4 book ai didi

encryption - 节点js : How to encrypt and decrypt using public-private key pair using crypto module?

转载 作者:行者123 更新时间:2023-12-05 08:58:22 25 4
gpt4 key购买 nike

我必须使用加密模块在 Node js 中编写代码(因为我不允许使用除 MIT 许可之外的任何模块)。我需要生成一个 key 对并使用公钥加密一些消息并使用私钥对其进行解密。第一部分即 key 对的生成已完成。我不知道如何使用加密模块使用相同的 key 对加密和解密某些消息。

最佳答案

这应该做你想做的:

const { generateKeyPairSync, publicEncrypt, privateDecrypt } = require('crypto');

//generate a key pair RSA type encryption with a .pem format
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',

}
});

// print out the generated keys
console.log(`PublicKey: ${publicKey}`);
console.log(`PrivateKey: ${privateKey}`);

//message to be encrypted
var toEncrypt = "my secret text to be encrypted";
var encryptBuffer = Buffer.from(toEncrypt);

//encrypt using public key
var encrypted = publicEncrypt(publicKey,encryptBuffer);

//print out the text and cyphertext
console.log("Text to be encrypted:");
console.log(toEncrypt);
console.log("cipherText:");
console.log(encrypted.toString());

//decrypt the cyphertext using the private key
var decryptBuffer = Buffer.from(encrypted.toString("base64"), "base64");
var decrypted = privateDecrypt(privateKey,decryptBuffer);

//print out the decrypted text
console.log("decripted Text:");
console.log(decrypted.toString());

它生成可用于加密和解密消息的 key 对。

关于encryption - 节点js : How to encrypt and decrypt using public-private key pair using crypto module?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23612355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com