2014-10-04 64 views
-1

任何人都可以幫助我將下面的Python腳本轉換爲PHP嗎?Python到PHP - Base64編碼SHA256

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)); 

但我想得到通過使用和數組,而不是一個引號轉義的字符串所期望的結果...

+0

看一看['hash'](http://php.net/hash)和['base64_encode'](http://php.net/base64_encode )。 – Gumbo 2014-10-04 17:46:29

+0

@Gumbo,他的問題與這些功能無關 - 而且他已經有用PHP編寫的示例代碼。 – 2014-10-04 17:56:20

+0

@MartinKonecny他在我評論3分鐘後補充道。 – Gumbo 2014-10-04 18:15:05

回答

0

Paul Crovella,您指出了正確的方向。 我要做一個字符串的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)); 

然後我得到期望的結果,同在Python腳本:
oWVxV3hhr8 + LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k =

0

你需要用PHP json_encode

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

這些功能都需要一個關聯數組來代替蟒蛇json.dumps並將其轉換成字符串表示。那就是你做一個散列/ base64編碼的字符串。

+0

我試過了,但後來我得到以下字符串: atbx1Uf4ybQny9ENYejHvDHP9Wm7qNqyeagnBp92m2Y = – 2014-10-04 17:56:21

+0

是的,這似乎是一個大問題:/。你可以用Python工作,在執行'json.dumps'時刪除任何空格嗎? http://stackoverflow.com/questions/16311562/python-json-without-whitespaces – 2014-10-04 18:00:50