节点js:如何使用加密模块使用公钥 - 私钥对加密和解密?

时间:2014-05-12 13:09:50

标签: encryption

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

2 个答案:

答案 0 :(得分:1)

这应该做您想要的:

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());

它会生成一个密钥对,可用于加密和解密消息。

答案 1 :(得分:0)

在Crypto lib的节点文档中有以下示例:

var crypto = require('crypto');
var alice = crypto.getDiffieHellman('modp5');
var bob = crypto.getDiffieHellman('modp5');

alice.generateKeys();
bob.generateKeys();

var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');

/* alice_secret and bob_secret should be the same */
console.log(alice_secret == bob_secret);

此示例显示如何计算共享secret,然后可以将其与.createCipher().createDecipher()一起使用,如下所示:

var encrypt64 = function(aMsg, aSecret) {
  var cipher, tRet;
  cipher = crypto.createCipher('aes-256-cbc', aSecret);
  tRet = cipher.update(aMsg, 'utf8', 'base64');
  tRet += cipher.final('base64');
  return tRet;
};

var decrypt64 = function(aMsg, aSecret) {
  var decipher, tRet;
  decipher = crypto.createDecipher('aes-256-cbc', aSecret);
  tRet = decipher.update(aMsg.replace(/\s/g, "+"), 'base64', 'utf8');
  tRet += decipher.final('utf8');
  return tRet;
};