首页 > 解决方案 > PHP 的 openssl_sign 在 Node JS 中等效

问题描述

我正在(慢慢地)学习 Node JS 并尝试用它来代替我拥有的 PHP 脚本。我需要签署一个我用 SSL 组装的字符串以传递给curl请求。

在 PHP 中,我是这样做的:

$sig = '2018-08-24T17:33:41Z:abcdef:/path/to/api';

$pkeyid = openssl_pkey_get_private("file://YourMomGoesToCollege.pem"); 

// Sign 'sig' with private key
if(openssl_sign($sig, $signed_signature, $pkeyid, "sha256WithRSAEncryption")) {

  openssl_free_key($pkeyid);

  //Set curl header options ...
  curl_setopt($ch, CURLOPT_HTTPHEADER,
    [
    "X-Apple-CloudKit-Request-SignatureV1: " . base64_encode($signed_signature),
  ]
);

}

所以我试图生成 evuivalent $signed_signature,但我不知道如何进行。似乎 Node 的Crypto可以做类似的事情,但它的参数似乎不同。这是我最好的猜测:

const crypto = require('crypto')
const sign = crypto.createSign('SHA256')

sign.write(sig)
sign.end()

const privateKey = __dirname + 'YourMomGoesToCollege.pem'
var signedSignature = sign.sign(privateKey, 'hex')

var readyForCurl = Buffer.from(signedSignature).toString('base64')

我在正确的轨道上吗?

标签: phpnode.jsopenssl

解决方案


以您的工作为起点并进行一些小的修改,以下代码段将打印相同的签名(base64 编码):

PHP:

$data = 'some data to sign';
$key = openssl_pkey_get_private('file://private.pem'); 

if(openssl_sign($data, $signature, $key, 'sha256WithRSAEncryption')) {
  openssl_free_key($key);
  $signature_b64 = base64_encode($signature);
  echo($signature_b64."\n");
}

节点JS:

const crypto = require('crypto');
const sign = crypto.createSign('SHA256');
const fs = require('fs')

sign.write('some data to sign');
sign.end();

const key = fs.readFileSync('private.pem');
signature_b64 = sign.sign(key, 'base64');
console.log(signature_b64);

diff- 两个:

$ diff <(php sign.php) <(node sign.js)

显示输出相同。

我使用了这个资源:iotdb-crypto-example


推荐阅读