如何使用 PHP 创建签名

How to create signature using PHP

我需要使用 API 但首先要登录,我需要创建签名。

1. Concatenate the API key with the current timestamp in the format below:
<<APIKEY>>_<<timestamp(yyyy'-'MM'-'ddTHH:mm:ss.fffZ)>>

这一步很简单:

hash('sha256', $data);

结果是: 9952375a30708b46739986482303cae30ad51fc9a362b5794d298dfc22f7ec02 这是正确的结果

下一步是:

2. The combination of the created signature along with the provided API secret key will act as the
digital signature of the call.

我有 API 个密钥,例如:

    -----BEGIN PUBLIC KEY-----
9IGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCgBSU90PX4WyXFAZ/+M84dJNEi
/0j5OermfydTU4g2JvnpO6BOQjNpb5+mOLjVoij7DWTdDtx1WThRm04N3DVuyh+a
5cledvMbcngvyiXpQCdskT9bVmI4QLbmRny46S7MER1jhziMQRfRw9gbmlB2iCEq
n21kDr842Q+WDtLE4QIDAQA9
-----END PUBLIC KEY-----

如何结合创建的签名和提供的 API 密钥获得数字签名?

有一个 Python 示例,例如:

key = api_key + '_' + timestamp

print "message", key

sha_hash = hashlib.sha256(key).hexdigest()

print "sha256 hash:", sha_hash


rsa_key = RSA.importKey(pub_key)
cipher = PKCS1_v1_5.new(rsa_key)
signature = base64.encodestring(cipher.encrypt(sha_hash))

但是如何使用 PHP 获得签名?

虽然有多种方法可以实现此目的,但我建议使用 openssl_public_encrypt 方法。还有其他 crypt 函数甚至是 RSA 的纯 PHP 实现,但它们可能不像 openSSL 将在 linux 系统上那样最新且维护良好.不要忘记最近几年 SSL/TLS 的所有中断。从淘汰旧协议和较弱的密码到 POODLE 类型漏洞利用的一切。

如果出于某种原因这不是一个选项,我可能会研究 phpseclib。 https://github.com/phpseclib/phpseclib

真正可能归结为什么对您的项目最有意义...OS、可移植性、速度等

这里是 Python 片段转换为等价的 PHP 代码。

<?php
$key = $api_key . '_' . $timestamp;

echo "message:" . $key;

$sha_hash = hash('sha256', $key);

echo "sha256 hash:" .  $sha_hash;

$rsa_key = "your public key goes in here"; //see https://www.php.net/manual/en/function.openssl-pkey-get-public.php

openssl_public_encrypt($sha_hash, $encrypted, $rsa_key);
$signature = base64_encode($encrypted);