Python相当于php base64_encode

时间:2017-04-21 05:48:15

标签: php python encoding base64

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)

输出:

&#39; fb2f85c88567f3c8ce9b799c7c54642d0c7b41f6&#39; ZmIyZjg1Yzg4NTY3ZjNjOGNlOWI3OTljN2M1NDY0MmQwYzdiNDFmNg ==

PHP和Python SHA1都运行良好,但python中的base64.encodestring()返回的值与PHP中的base64_encode()不同。

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

3 个答案:

答案 0 :(得分:2)

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

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

base64.encodestring期望字符串,同时为它提供十六进制表示。

答案 1 :(得分:1)

您正在使用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编码,你会得到不同的结果 只要你保持一致,你编码的无关紧要。

答案 2 :(得分:1)

base64.b64encode(s.digest())有正确的回复