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

时间:2017-08-03 04:56:34

标签: javascript node.js encryption rsa jose

我正在尝试使用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. 我假设我应该用私钥解密。但这只是一个假设。这些示例都没有显示使用公钥/私钥对,只使用一个密钥。
  2. 我假设加密的结果可以被强化并变成缓冲区并传递到decrypt,但可能情况并非如此。
  3. 这是如何运作的?

1 个答案:

答案 0 :(得分:0)

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

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

  3. decrypt功能更改为:

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