简体   繁体   English

PHP 的 openssl_sign 等效于 Node JS

[英]PHP's openssl_sign Equivalent in Node JS

I am (slowly) learning Node JS and trying to use it in place of a PHP script I have.我正在(慢慢地)学习 Node JS 并尝试用它来代替我拥有的 PHP 脚本。 I need to sign a string I have assembled with SSL to pass on to a curl request.我需要对我用 SSL 组装的字符串进行签名以传递给curl请求。

In PHP, this is how I've done it:在 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),
  ]
);

}

So I'm trying to generate the evuivalent of $signed_signature , but I'm not sure how to proceed.所以我试图生成$signed_signature ,但我不确定如何继续。 It seems like Node's Crypto can do something similar, but its parameters seem different. Node 的Crypto似乎可以做类似的事情,但它的参数似乎不同。 This is my best guess:这是我最好的猜测:

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')

Am I on the right track?我在正确的轨道上吗?

Using your work as a starting point and doing some minor modifications, the following snippets result in the same signature being printed (base64-encoded): 使用您的工作作为起点并进行一些小修改,以下代码段会导致打印相同的签名(base64编码):

PHP: 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: 节点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 -ing the two: diff -ing两个:

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

shows the outputs are the same. 显示输出是相同的。

I used this resource: iotdb-crypto-example 我使用了这个资源: iotdb-crypto-example

Hope this will helpful if you have passphrase:如果您有密码,希望这会有所帮助:

const crypto = require('crypto');

function makeSign(privateKey, password, data){
    return crypto.createSign('sha1').update(JSON.stringify(data)).sign({
        format: 'pem',
        key: privateKey,
        passphrase: password
    }, 'base64');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM