php实现hmac sha1,PHP:如何生成字符串的hmac SHA1签名?

我正在尝试使用PHP连接到API并需要正确的签名.

他们的文件逐字记录:

The command string needs to hashed using HMAC SHA-1 hashing algorithm

against the API secret key. The resulting byte array should be Base64

encoded in UTF-8 format so that it can be passed via http.

To generate the signature you have to lower case the complete list of

request parameters and sort them alphabetically via the field for each

field-value pair. The resulting string to sign from the previous

example with a secret key VDaACYb0LV9eNjTetIOElcVQkvJck_J_QljX would

be:

apikey=mivr6x7u6bn_sdahobpjnejpgest35exqjb8cg20&command=deployvirtualmachine&serviceofferingid=21624abb-764e-4def-81d7-9fc54b5957fb&templateid=54c83a5e-c548-4d91-8b14-5cf2d4c081ee&zoneid=1128bd56-b4d9-4ac6-a7b9-c715b187ce11

Resulting in a signature value of:

ahlpA6J1Fq6OYI1HFrMSGgBt0WY%3D

示例尝试:

$string = 'apikey=mivr6x7u6bn_sdahobpjnejpgest35exqjb8cg20&command=deployvirtualmachine&serviceofferingid=21624abb-764e-4def-81d7-9fc54b5957fb&templateid=54c83a5e-c548-4d91-8b14-5cf2d4c081ee&zoneid=1128bd56-b4d9-4ac6-a7b9-c715b187ce11

';

$string = utf8_encode(strtolower($string));

$key = 'VDaACYb0LV9eNjTetIOElcVQkvJck_J_QljX';

$signature = hash_hmac('sha1', $string , $key);

print 'SIGNATURE:'.$signature.'
';

if($signature=='ahlpA6J1Fq6OYI1HFrMSGgBt0WY%3D'){

print 'SUCCESS';

}else{

print 'FAIL';

}

结果:9077d90baa7ab8913811b64a50814b640dce60eb

假设是:ahlpA6J1Fq6OYI1HFrMSGgBt0WY =

问题:结果与他们的文档不符.知道我做错了什么吗?

解决方法:

您的签名应该像这样生成:

$signature = urlencode(base64_encode(hash_hmac('sha1', $string , $key, true)));

最后一个参数的默认值为false.然后它将返回十六进制编码的字符串而不是原始字节.然后你必须按照文档中的说明对字节进行base64_encode.然后你必须对它进行urlencode,因为=必须进行转换

标签:hmac,php,hmacsha1

来源: https://codeday.me/bug/20190827/1744948.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值