0

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?

0

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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.

3 Comments

then how to get the raw output in python?
I think it's easier to just remove the true from the sha1('ABC', true).
That's what I'm saying. If you remove the true, you should get the same in both PHP and Python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.