Python到PHP-Base64编码SHA256

Python到PHP-Base64编码SHA256,php,python,sha256,Php,Python,Sha256,有人能帮我把下面的Python脚本转换成PHP吗 data = json.dumps({'text': 'Hello world'}) content_sha256 = base64.b64encode(SHA256.new(data).digest()) content_sha256的值应为 OWVxV3Hr8+LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k= 我已尝试使用base64_encode函数,并且只有在使用字符串时才会得到所需的结果: $data_string

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

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

content_sha256 = base64.b64encode(SHA256.new(data).digest())
content_sha256的值应为

OWVxV3Hr8+LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k=

我已尝试使用base64_encode函数,并且只有在使用字符串时才会得到所需的结果:

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

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

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

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

指出了正确的方向。 在通过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=

看一看,@Gumbo,他的问题与那些函数无关-他已经有了用PHP编写的示例代码。@MartinKonecny他在我的评论三分钟后补充了这一点。我已经尝试过了,但我得到了以下字符串:atbx1uf4ybqny9enyejhvdhp9wm7nqyeagnb92m2y=Yea,这似乎是个大问题:/。在执行json.dumps时,您可以使用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));