简体   繁体   English

SHA256没有在PHP中生成正确的哈希

[英]SHA256 is not generating right hash in php

Following is the procedure for generating a sha256 based hashed. 以下是生成基于sha256的哈希的过程。

Generated Hash 生成的哈希

The hash query string parameter is to be followed by the generated hash for that specific request. 哈希查询字符串参数后跟该特定请求的生成哈希。 To generate the hash: 生成哈希:

  1. Take the body of the HTTP POST request 取HTTP POST请求的正文
  2. Add the provided API Secret to the end of the body 将提供的API Secret添加到正文的末尾
  3. Converts it to SHA256 and converts the hashed message to hexadecimal format 将其转换为SHA256并将散列的消息转换为十六进制格式

For example, assuming the provided API Secret is "secretapikey" and the HTTP POST body contains the following: 例如,假设提供的API机密为“ secretapikey”,并且HTTP POST正文包含以下内容:

{ "apiKey": 123, "invoiceId": 1 }

The generated hash will be: 生成的哈希将为:

d48cf8a852713844603d7c8cbefb3e81cfb29e7540d98f06affdf58322c1038e

Below is the steps taken to produce the above generated hash: 以下是生成上面生成的哈希的步骤:

HTTP POST Body => { "apiKey": 123, "invoiceId": 1 } HTTP POST { "apiKey": 123, "invoiceId": 1 } => { "apiKey": 123, "invoiceId": 1 }

Secret => secretapikey 秘密=> secretapikey

Text to be hashed => { "apiKey": 123, "invoiceId": 1 }secretapikey 要散列的文本=> { "apiKey": 123, "invoiceId": 1 }secretapikey

SHA-256 Hash => d48cf8a852713844603d7c8cbefb3e81cfb29e7540d98f06affdf58322c1038e SHA-256哈希=> d48cf8a852713844603d7c8cbefb3e81cfb29e7540d98f06affdf58322c1038e

I have to concatinate two strings ( { "apiKey": 123, "invoiceId": 1 }secretapikey ) and then hash them to send to an api end point. 我必须合并两个字符串( { "apiKey": 123, "invoiceId": 1 }secretapikey ),然后将它们哈希以发送到api端点。 But the Hash generated by following code is not according to hash generated by an online sha256:- 但是,以下代码生成的哈希值与在线sha256生成的哈希值不同:-

$secretapikey = "secretapikey";
$postbody = array();
$postbody['apiKey'] = "123";
$postbody['invoiceId'] = 1;

$jpb = json_encode($postbody);

$hashed = $jpb.$secretapikey; //Here is Problem. It is not concatenated according to requirement


$result = hash('SHA256', $hashed);

echo $result;

This is the value of $result 这是$result的值

d2c5d184be42ff4ae3a0046d0727c026f38c1e92f8960cb9d17d496c7b89b7b3

whereas it should be 而应该是

d48cf8a852713844603d7c8cbefb3e81cfb29e7540d98f06affdf58322c1038e

hash('SHA256', $hashed); is doing its job right 做得很好

and $hashed = $jpb.$secretapikey; $hashed = $jpb.$secretapikey; is joining the two strings correctly. 正确地连接了两个字符串。

The reason you don't get the hash you expect is that the JSON you use for the test is 您没有获得期望的哈希的原因是,用于测试的JSON是

{ "apiKey": 123, "invoiceId": 1 }

while the JSON produced by json_encode($postbody); 而由json_encode($postbody);生成的JSON json_encode($postbody);

is {"apiKey":123,"invoiceId":1} {"apiKey":123,"invoiceId":1}

without spaces. 没有空格。

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

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