Python to PHP - Base64 encode SHA256


Python to PHP - Base64 encode SHA256

有人能帮我把下面的Python脚本转换成PHP吗?

data = json.dumps({'text': 'Hello world'})
content_sha256 = base64.b64encode(SHA256.new(data).digest())

content_sha256的值应为

oWVxV3hhr8+LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k=

我尝试过使用base64_encode函数,只有使用字符串才能得到所需的结果

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

但我想通过使用和数组来获得所需的结果,而不是用引号转义的字符串。。。

您需要用php json_encode 替换python json.dumps

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

这两个函数都采用关联数组,并将其转换为字符串表示。然后就是您对其进行hash/base64编码的字符串。

Paul Crovella,你指出了正确的方向。在通过base64发送json编码的变量之前,我必须对其进行字符串替换,以获得与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));

然后我得到了所需的结果,与Python脚本中的结果相同:
oWVxV3hhr8+LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k=