Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode text to base64 in python

I am trying to encode a text string to base64.

i tried doing this :

name = "your name" print('encoding %s in base64 yields = %s\n'%(name,name.encode('base64','strict'))) 

But this gives me the following error:

LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs 

How do I go about doing this ? ( using Python 3.4)

like image 578
sukhvir Avatar asked Apr 18 '14 23:04

sukhvir


People also ask

How do you convert text to base64 in Python?

To convert a string into a Base64 character the following steps should be followed: Get the ASCII value of each character in the string. Compute the 8-bit binary equivalent of the ASCII values. Convert the 8-bit characters chunk into chunks of 6 bits by re-grouping the digits.

How do I encode a string in base64?

If we were to Base64 encode a string we would follow these steps: Take the ASCII value of each character in the string. Calculate the 8-bit binary equivalent of the ASCII values. Convert the 8-bit chunks into chunks of 6 bits by simply re-grouping the digits.

What is base64 encoding and decoding?

What Does Base64 Mean? Base64 is an encoding and decoding technique used to convert binary data to an American Standard for Information Interchange (ASCII) text format, and vice versa.


2 Answers

Remember to import base64 and that b64encode takes bytes as an argument.

import base64 base64.b64encode(bytes('your string', 'utf-8')) 
like image 78
Alexander Ejbekov Avatar answered Sep 23 '22 10:09

Alexander Ejbekov


It turns out that this is important enough to get it's own module...

import base64 base64.b64encode(b'your name')  # b'eW91ciBuYW1l' base64.b64encode('your name'.encode('ascii'))  # b'eW91ciBuYW1l' 
like image 29
mgilson Avatar answered Sep 21 '22 10:09

mgilson