简体   繁体   English

Python至PHP-Base64编码SHA256

[英]Python to PHP - Base64 encode SHA256

Can anyone help me with converting the following Python script to PHP? 谁能帮助我将以下Python脚本转换为PHP?

data = json.dumps({'text': 'Hello world'})

content_sha256 = base64.b64encode(SHA256.new(data).digest())

The value of content_sha256 should be content_sha256的值应为

oWVxV3hhr8+LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k= oWVxV3hhr8 + LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k =

I have tried to use the base64_encode function, and will only get the desired result if I use the string: 我尝试使用base64_encode函数,并且仅在使用字符串时才能获得所需的结果:

$data_string = "{\"text\": \"Hello world\"}";
base64_encode(hash("sha256", $data_string, true));

but I want to get the desired result by using and array, not a quote-escaped string... 但是我想通过使用and数组而不是用引号转义的字符串来获得期望的结果...

You need to replace python json.dumps with php json_encode 您需要用php json_encode替换python json.dumps

$data_string = json_encode(array('text' => 'Hello world'));
base64_encode(hash("sha256", $data_string, true));

Both of these functions take an associative array and transform it into a string representation. 这两个函数都采用关联数组并将其转换为字符串表示形式。 It is then the string that you do a hash/base64 encoding on. 然后是在其上执行哈希/ base64编码的字符串。

Paul Crovella , you pointed out the correct direction. Paul Crovella ,您指出了正确的方向。 I have to do a string replace on the json encoded variable before I send it through the base64, to get the same string as the one made by Python: 我必须先对json编码的变量进行字符串替换,然后再将其通过base64发送,以获取与Python生成的字符串相同的字符串:

$data_array = array("text" => "Hello world");
$data_string_json_encoded = json_encode($data_array);
$data_string_json_encoded_with_space_after_colon = str_replace(":", ": ", $data_string_json_encoded);

$data_string_base64 = base64_encode(hash("sha256", $data_string_json_encoded_with_space_after_colon , true));

Then I get the desired result, the same as in the Python script: 然后,我得到了所需的结果,与Python脚本中的结果相同:
oWVxV3hhr8+LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k= oWVxV3hhr8 + LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k =

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

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