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

标签 encryption

我必须使用加密模块在 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/

相关文章:

python-3.x - 单 key 加密,多 key 解密

encryption - 从文件中查找加密算法

ssl - webroot 不会检测 Let's Encrypt 证书创建的根路径

java - 制作加密程序,我收到语法错误,但我不知道为什么

encryption - 加密指定的备用数据流 - NTFS、XP

java - 如何使用 MD5 重新哈希存储在数据库中的密码?

database - 联邦税号应该在数据库中加密吗?

java - 为 Android Password Safe 应用程序选择存储数据的最佳解决方案

mysql - 安装 MariaDB 静态加密

java - 解密时出现 RSA BadPaddingException