2017-04-21 15 views
0

PHPPythonの等価

<?php 

$string = base64_encode(sha1('ABCD' , true)); 
echo sha1('ABCD'); 
echo $string; 
?> 

出力:

fb2f85c88567f3c8ce9b799c7c54642d0c7b41f6

+ Y + FyIVn88jOm3mcfFRkLQx7QfY =

パイソン

import base64 
import hashlib 

s = hashlib.sha1() 
s.update('ABCD') 
myhash = s.hexdigest() 
print myhash 
print base64.encodestring(myhash) 

出力:

'fb2f85c88567f3c8ce9b799c7c54642d0c7b41f6' ZmIyZjg1Yzg4NTY3ZjNjOGNlOWI3OTljN2M1NDY0MmQwYzdiNDFmNg ==

PHPやPython SHA1の両方が正常に動作しますが、Pythonでbase64.encodestring()はPHPでbase64_encode()に比べて異なる値を返します。

PythonでPHP base64_encodeの同等のメソッドは何ですか?

答えて

2

使用sha1.digest()代わりbase64.encodestring

s = hashlib.sha1() 
s.update('ABCD') 
print base64.encodestring(s.digest()) 

sha1.hexdigest()のは、文字列に期待しています。

1

あなたはPHPとPythonで異なるsha1結果をエンコードしています。 PHPで

:Pythonで

// The second argument (true) to sha1 will make it return the raw output 
// which means that you're encoding the raw output. 
$string = base64_encode(sha1('ABCD' , true)); 

// Here you print the non-raw output 
echo sha1('ABCD'); 

s = hashlib.sha1() 
s.update('ABCD') 

// Here you're converting the raw output to hex 
myhash = s.hexdigest() 
print myhash 

// Here you're actually encoding the hex version instead of the raw 
// (which was the one you encoded in PHP) 
print base64.encodestring(myhash) 

あなたが生と非生の出力をエンコードBASE64場合は、異なる結果が得られます。
一貫性がある限り、エンコードするのは重要ではありません。あなたはそれをそれの16進表現を与えながら

+0

を持っていますか? –

+1

'sha1( 'ABC'、true)'から 'true'を削除する方が簡単だと思います。 –

+1

それは私が言っていることです。 'true'を削除した場合、PHPとPythonの両方で同じ結果を得なければなりません。 –

1

base64.b64encode(s.digest())はPythonで生の出力を取得する方法を、正しい応答