How to encode text to base64 in python

139,711

Solution 1

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

import base64
base64.b64encode(bytes('your string', 'utf-8'))

Solution 2

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'

Solution 3

1) This works without imports in Python 2:

>>>
>>> 'Some text'.encode('base64')
'U29tZSB0ZXh0\n'
>>>
>>> 'U29tZSB0ZXh0\n'.decode('base64')
'Some text'
>>>
>>> 'U29tZSB0ZXh0'.decode('base64')
'Some text'
>>>

(although this doesn't work in Python3 )

2) In Python 3 you'd have to import base64 and do base64.b64decode('...') - will work in Python 2 too.

Solution 4

For py3, base64 encode and decode string:

import base64

def b64e(s):
    return base64.b64encode(s.encode()).decode()


def b64d(s):
    return base64.b64decode(s).decode()

Solution 5

To compatibility with both py2 and py3

import six
import base64

def b64encode(source):
    if six.PY3:
        source = source.encode('utf-8')
    content = base64.b64encode(source).decode('utf-8')
Share:
139,711
sukhvir
Author by

sukhvir

Updated on July 05, 2022

Comments

  • sukhvir
    sukhvir almost 2 years

    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)

  • sukhvir
    sukhvir about 10 years
    gives me this error : import base64 >>> base64.b64encode(b'%s'%name) SyntaxError: multiple statements found while compiling a single statement
  • mgilson
    mgilson about 10 years
    the >>> was copied from my terminal prompt. Leave those out.
  • sukhvir
    sukhvir about 10 years
    i did ... Those are from my terminal prompt
  • sukhvir
    sukhvir about 10 years
    how do i remove the leading b when printing this?
  • sukhvir
    sukhvir about 10 years
    How do i remove the leading b during print out
  • mgilson
    mgilson about 10 years
    You need to decode it from bytes into a string using some encoding -- e.g. ascii or utf8. (b'home'.decode('ascii') for example)
  • mgilson
    mgilson about 10 years
    @sukhvir -- check my response on the other answer ;-)
  • Eryk Sun
    Eryk Sun about 10 years
    I suppose that syntax error is yet another IDLE 'feature'. It should support pasting multiple statements in the shell.
  • Stevoisiak
    Stevoisiak over 6 years
    What about decoding the string afterwards?
  • mgilson
    mgilson over 6 years
    @StevenVascellaro -- base64.b64decode or one of the variants depending on the alphabet used to encode ...
  • dkato
    dkato over 6 years
    Please consider to translate your into Python 3 executable, since original post assumed it.
  • Nico Haase
    Nico Haase over 6 years
    There are some older answers to this question. Can you comment what makes your's better?
  • ujjawal sharma
    ujjawal sharma over 6 years
    @NicoHaase .. This code i had developed which can convert a string from String to Base64 and vice versa. You can directly run it as a python script.
  • Nico Haase
    Nico Haase over 6 years
    That does not really answer my question: the OP is not asking for a script that makes everything possible, but for the purest call of converting a string to base64
  • ujjawal sharma
    ujjawal sharma over 6 years
    @NicoHaase I was looking for solution to this question myself but the solutions provided were not enough for me. I saw the code somewhere else and then i wrote the whole solution at one place.
  • tarikki
    tarikki over 5 years
    Using this with GCP Deployment manager to base64 encode secrets.
  • Henrik Nordvik
    Henrik Nordvik about 4 years
    Be careful with this one! It adds newlines \n into the output about every 58 character. >>> 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx‌​x'.encode('base64') 'eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh‌​4eHh4eHh4eHh4eHh4\ne‌​Hh4\n'
  • Tagar
    Tagar about 4 years
    per BASE64 Standard tools.ietf.org/html/rfc4648#section-3.3 newline characters must be ignored: "Note that this means that any adjacent carriage return/line feed (CRLF) characters constitute "non-alphabet characters" and are ignored." Also the new line characters are defined in the Standard as well tools.ietf.org/html/rfc4648#section-3.1 "As such, MIME enforces a limit on line length of base 64-encoded data to 76 characters"
  • Eight Rice
    Eight Rice almost 3 years
    TypeError: encode() missing 1 required positional argument: 'output'
  • S.B
    S.B almost 3 years
    This is the correct answer ! base64 is binary-to-text encoding I don't know why python's base64 module doesn't convert it back to string by itself...