1

Can anyone help me with converting the following Python script to PHP?

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

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

The value of content_sha256 should be

oWVxV3hhr8+LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k=

I have tried to use the base64_encode function, and will only get the desired result if I use the string:

$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...

2 Answers2

0

You need to replace python json.dumps with php json_encode

$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.

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • I have tried that, but then I get the following string: atbx1Uf4ybQny9ENYejHvDHP9Wm7qNqyeagnBp92m2Y= – Vebjørn Reinsberg Oct 04 '14 at 17:56
  • 1
    Yea, that seems to be a big issue :/. Can you work in Python to remove any of the spaces when doing `json.dumps`? http://stackoverflow.com/questions/16311562/python-json-without-whitespaces – Martin Konecny Oct 04 '14 at 18:00
0

Paul Crovella, you pointed out the correct direction. 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:

$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:
oWVxV3hhr8+LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k=

Community
  • 1
  • 1