首页 > 解决方案 > RSAES-PKCS1- V1_5 使用 NodeJs 加密的公共加密

问题描述

我正在尝试使用 NodeJs 加密模块将加密数据发送到远程服务器。

根据 API 文档,payload 需要使用 AES-256 算法和随机生成的 KEY 和 IV 进行加密。

然后使用 RSAES-PKCS1-V1_5 标准使用共享私钥对随机生成的 KEY 和 IV [上图] 进行加密。

最后,使用 RSASSA-PKCS1-V1_5 签名方案使用私钥对加密的有效负载进行签名,然后进行 SHA1 哈希处理。

完成后,我编写一个 HTTP 请求并将加密的 KEY、IV、加密的有效负载和签名传递给删除服务器。

在密码学方面我不是专家,所以我确信我在某个地方做错了什么。

服务器能够验证签名,这让我确信共享私钥文件没有问题。

但是,服务器无法解密解密有效负载所需的加密 KEY 和 IV。

我正在使用下面的代码进行测试:

const crypto = require('crypto');
const fs = require('fs');

//Generate random KEY and IV
const randomKey = crypto.randomBytes(32);
const randomIV = crypto.randomBytes(16);

//Load private key from disk
const privateKey = fs.readFileSync(__dirname + '/private.key');

//Get data payload that should be encrypted with AES-256
const payload = 'Payload to be sent';

//Encrypt payload with AES-256
const cipher = crypto.createCipheriv('aes-256-cbc', randomKey, randomIV);
const encryptedPayload = Buffer.concat([cipher.update(payload), cipher.final()]);

//Sign the encrypted payload using the RSASSA-PKCS1-V1_5 algorithm
const signer = crypto.createSign('RSA-SHA1');
signer.update(encryptedPayload);
signer.end();
const signature = signer.sign(privateKey); //Sign with the private key

//Encrypt both KEY and IV
const encryptOptions = {
  key: privateKey,
  padding: constants.RSA_PKCS1_PADDING
}
const encryptedKey = crypto.publicEncrypt(encryptOptions, randomKey);
const encryptedIV = crypto.publicEncrypt(encryptOptions, randomIV);

//A function that encodes Buffer type data to base64
const encode = buffer => buffer.toString('base64');

const request = {
  encryptedKey: encode(encryptedKey),
  encryptedIV: encode(encryptedIV),
  encryptedPayload: encode(encryptedPayload),
  signature: encode(signature)
};

const endPoint = require('./end-point');
endPoint.call(request);
//-> Server successfully verifies signature but fails to decrypt encrypted KEY and IV

有人可以指出我做错了什么吗?

标签: node.jsrsanode-crypto

解决方案


推荐阅读