Gopakumar N G
Gopakumar N G

Reputation: 1843

Python equivalent of php base64_encode

PHP

<?php

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

Output:

fb2f85c88567f3c8ce9b799c7c54642d0c7b41f6

+y+FyIVn88jOm3mcfFRkLQx7QfY=

Python

import base64
import hashlib

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

Output:

'fb2f85c88567f3c8ce9b799c7c54642d0c7b41f6' ZmIyZjg1Yzg4NTY3ZjNjOGNlOWI3OTljN2M1NDY0MmQwYzdiNDFmNg==

Both the PHP and Python SHA1 works fine, but the base64.encodestring() in python returns a different value compared to base64_encode() in PHP.

What is the equivalent method for PHP base64_encode in Python?

Upvotes: 0

Views: 3546

Answers (3)

napuzba
napuzba

Reputation: 6298

use sha1.digest() instead of sha1.hexdigest()

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

The base64.encodestring expects to the string while you give it the hex representation of it.

Upvotes: 2

vako
vako

Reputation: 111

base64.b64encode(s.digest()) have correct response

Upvotes: 3

M. Eriksson
M. Eriksson

Reputation: 13645

You're encoding different sha1 results in PHP and Python.

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

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

If you base64 encode the raw and non-raw output, you will get different results.
It doesn't matter which you encode, as long as you're consistent.

Upvotes: 1

Related Questions