Python 相当于 php base64_encode

Python equivalent of php base64_encode

PHP

<?php

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

输出:

fb2f85c88567f3c8ce9b799c7c54642d0c7b41f6

+y+FyIVn88jOm3mcfFRkLQx7QfY=

Python

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 returns 中的 base64.encodestring()base64_encode() 相比是不同的值在 PHP.

PHP base64_encode 在 Python 中的等效方法是什么?

您在 PHP 和 Python 中编码了不同的 sha1 结果。

在PHP中:

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

在Python中:

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 编码,您将得到不同的结果。
只要您保持一致,编码哪种并不重要。

使用sha1.digest()代替sha1.hexdigest()

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

base64.encodestring 需要字符串,而您给它十六进制表示。

base64.b64encode(s.digest()) 回答正确