Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a difference between binascii.b2a_base64() and base64.b64encode()?

I'm trying to understand some divergent behavior I'm seeing with the following two functions:

def hex_to_64(string):
    hex_string = binascii.a2b_hex(string)
    return binascii.b2a_base64(hex_string)

def hex_to_64_2(string):
    hex_string = binascii.a2b_hex(string)
    return base64.b64encode(hex_string)

If I pass in a hex string to the former, I get it back with a newline at the end, and the latter without. Is there a reason for that?

like image 221
Venantius Avatar asked Jan 04 '14 22:01

Venantius


1 Answers

Nothing special, the implementators decided to do it that way. It is documented at binascii module.

Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char. The length of data should be at most 57 to adhere to the base64 standard.

If you don't feel comfortable with that just right strip it:

hex_to_64('aa').rstrip('\n')
>>>'qg=='

Hope this helps!

like image 126
Paulo Bu Avatar answered Nov 15 '22 04:11

Paulo Bu