PHP在Node JS中的openssl_sign等效

时间:2018-08-24 18:00:43

标签: php node.js openssl

我正在(慢慢地)学习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),
  ]
);

}

因此,我正在尝试生成$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')

我在正确的轨道上吗?

1 个答案:

答案 0 :(得分:3)

使用您的工作作为起点并进行一些小的修改,以下代码片段将导致打印相同的签名(以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");
}

Node 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

相关问题