Monday, November 9, 2009

Base64 in PHP and Python

Today I calculated a hash value based on strings encoded with Base64 encoding.

One in PHP, and one in Python. Both of them should return the same value, because the hashes were compared for verification.

So, in PHP, the code is

myHashFunction(base64_encode('original string')) 

And in Python, the code is

myHashFunction(base64.encodestring('original string'))

Dangerous! The results are different! Since the 'original string' was not as simple as that, I thought I had passed the wrong data. But after some checking, the results of base64_encode and base64.encodestring were different.

base64_encode('original string') returns "b3JpZ2luYWwgc3RyaW5n"

whereas base64.encodestring('original string') returns "b3JpZ2luYWwgc3RyaW5n\n"

More precisely, base64.encodestring added new-line character at the end (and every 76 chars I think), suitable for email attachment, whereas base64_encode does not.

An easy solution to make them identical is to add replace function to the Python version, to become: base64.encodestring('original string').replace('\n', '').

No comments:

Post a Comment