具有Node-Forge的SHA256摘要签名

时间:2019-02-03 17:19:53

标签: javascript node.js openssl cryptography lets-encrypt

我正在构建Node.js ACMEv2客户端,并尝试仅依赖单个加密库来使代码保持简单。本机节点加密模块不支持CSR,因此我不得不使用Node-Forge。到目前为止,一切正常,但是我很难使用Node-Forge查找等效代码:

const crypto = require('crypto');
const signer = crypto.createSign('RSA-SHA256').update(`${requestBase64Url.protected}.${requestBase64Url.payload}`, 'utf8');
const signature = signer.sign(this.keys.accountKey.privatePem, 'base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
console.log(signature);

输出为:

  

oZpJuZlNgU48t8l-39V1LUZScOPHTFzHDWYT6ttf1KBGnm6jNuGkogwc0QiANrt5h5z6mp0Wz3rPz7etxjby_znQsGuaGdxvtVDf30_6j0mN-Rh7OXkS489JK6kDSQRbhpoyulb75QZyhDoA2pbmqyPc6HnfnQ2gUGr8HZf3K_LnfXCAX807MAzXd_bOx2dE0NbnwoVQQgGG1u5s7Q9-DY1WNjolYmkTt_skNoXgbAKZwj-8x6oSbfGk5_7-mbuEXcxUAJuXmGQsHrHAp7lKBZ9ZhTyZUlZjEhfRYb7cMYHSAJccalMPC5y5uzrIQYILhGtuDcXBsY1rCanJw6eRqg

我还可以使用以下OpenSSL实现相同的输出(并将结果编码为base64url):

openssl dgst -sha256 -sign account.key -out signature.sha256 signature.b64

如何使用Node-Forge模块获得相同的结果?我没有运气就尝试了以下方法:

let messageDigest = forge.md.sha256.create();
messageDigest.update(`${requestBase64Url.protected}.${requestBase64Url.payload}`, 'utf8');
const accountKey = await forge.pki.privateKeyFromPem(this.keys.accountKey.privatePem);
request.signature = accountKey.sign(messageDigest);

输出为:

  

wqHCmknCucKZTcKBTjzCt8OJfsOfw5V1LUZScMOjw4dMXMOHDWYTw6rDm1_DlMKgRsKebsKjNsOhwqTCogwcw5EIwoA2wrt5wofCnMO6wprCnRbDj3rDj8OPwrfCrcOGNsOyw785w5DCsGvCmhnDnG_CtVDDn8OfT8O6wo9Jwo3DuRh7OXkSw6PDj0krwqkDSQRbwobCmjLCulbDu8OlBnLChDoAw5rClsOmwqsjw5zDqHnDn8KdDcKgUGrDvB3Cl8O3K8Oyw6d9cMKAX8ONOzAMw5d3w7bDjsOHZ0TDkMOWw6fDgsKFUEIBwobDlsOubMOtD34Nwo1WNjolYmkTwrfDuyQ2woXDoGwCwpnDgj_CvMOHwqoSbcOxwqTDp8O-w77CmcK7woRdw4xUAMKbwpfCmGQsHsKxw4DCp8K5SgXCn1nChTzCmVJWYxIXw5Fhwr7DnDHCgcOSAMKXHGpTDwvCnMK5wrs6w4hBwoILwoRrbg3DhcOBwrHCjWsJwqnDicODwqfCkcKq

1 个答案:

答案 0 :(得分:1)

我找到了答案,这要归功于:

  1. https://github.com/digitalbazaar/forge/issues/647
  2. https://repl.it/repls/RipeLatestOctal

基本上,forge将签名编码为二进制字符串,必须使用以下代码对其进行解码:

request.signature = Buffer.from(forge.util.binary.raw.decode(accountKey.sign(messageDigest)));