使用 node-jose,如何解密刚刚加密的数据?

Using node-jose, how do I decrypt the data I just encrypted?

我正在尝试使用 node-jose.

实现简单的 JOSE encryptdecrypt 函数

我的代码如下(使用Node 8.2.1编写)

const { JWE } = require('node-jose');

const jose = (publicKey, privateKey) => {
  async function encrypt(raw) {
    if (!raw) throw new Error('Missing raw data.')
    const buffer = new Buffer(JSON.stringify(raw));
    return JWE.createEncrypt(publicKey).update(buffer).final();
  }

  async function decrypt(encrypted) {
    if (!encrypted) throw new Error('Missing encrypted data.')
    const buffer = new Buffer(JSON.stringify(encrypted));
    return JWE.createDecrypt(privateKey).decrypt(buffer);
  }

  return { encrypt, decrypt }
}

module.exports = jose;

我使用 generate-rsa-keypair.

生成了一个 RSA 密钥对

所以通过这段代码测试加密方面工作正常

const { JWK } = require('node-jose');
const keygen = require('generate-rsa-keypair');
const jose = require('./src/utils/jose');

const rawKeys = keygen();

const makeKey = pem => JWK.asKey(pem, 'pem');

async function start() {
  const publicKey = await makeKey(rawKeys.public)
  const privateKey = await makeKey(rawKeys.private)

  const raw = {
    iss: 'test',
    exp: new Date().getTime() + 3600,
    sub: {
      test: 'This is a test',
    },
  };

  const { encrypt, decrypt } = jose(publicKey, privateKey);

  return encrypt(raw).then(encrypted => decrypt(encrypted));
}

return start().then((result) => {
  console.log('decrypted', result)
}, (err) => {
  console.error(err);
});

encrypted 结果是

{
  recipients: [ { encrypted_key: 'ciNiK6Unq30zCAXxIl2Dx9b8bZAi79qbpL1yUCwTFnSghFLrIZ11_D2ozt5on3r3ThUu96oDLZPcNShbqWPMV49NvQAsSNGdemhgzmTt3Lf3rJn1YiqvJvqf5NIXdmzjdoEZi-d9224mGpZGVKtIIFeT6-0hYgm5zNqq_aF_X2jy5IiF-mAGspNdXIk_KXPrTVbnU-XL9J5aAoG2Lp51Te1WzGA4Fjg4Ve5ZTzH6TLlQ5R5Ob_14liK-INrSi3armwXrtMgJcTmI_4oBtORtZp8AjaXzecFO_GzifvRVCSKx2vmpy9KaECpskMhZBHVx9RX9cvGKh7hq3Y7vsUucZw' } ],
  protected: 'eyJhbGciOiJSU0EtT0FFUCIsImtpZCI6IldLWS1ONDRXM2RnanA4U2ZxSlp3TldqV3AzUG1XZ29UczhjRDh3eWNSUWciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0',
  iv: 'wvqir2ewtQPfDHQtzl6IUg',
  ciphertext: 'ZwIrL_3739LI17rh3gWDUA6lXIL7ewkSh54FO_RwumC0qh9B0DcAr8RyXsfPbW19cV4u7SbZNSRP6B8qNOTy-2iENlqBISfE_kolDt8g5sg',
  tag: 'z8nwrJfRgOi1hYMBI9lGeQ'
}

但是当我尝试解密时我得到

Error: no key found
  at processKey (node_modules/node-jose/lib/jwe/decrypt.js:157:22)

使用node-jose的例子很少,所以我不确定以下

  1. 我假设我应该用私钥解密。但这只是一个假设。 None 个示例显示使用 public/private 个密钥对,只有一个密钥。
  2. 我假设加密的结果可以被字符串化并变成一个缓冲区并传递给 decrypt 但也许事实并非如此。

这是如何运作的?

  1. 使用public/private密钥对时,private密钥用于解密,public密钥用于加密

  2. JWEDecrypter.decrypt() 的输入是 JWEEncrypter.final() 的承诺输出。

将您的 decrypt 函数更改为:

async function decrypt(encrypted) {
  if (!encrypted) throw new Error('Missing encrypted data.')
  return JWE.createDecrypt(privateKey).decrypt(encrypted);
}