16

I'm trying to find an exact equivalent to javascript's function 'btoa', as I want to encode a password as base64. It appears that there are many options however, as listed here:

https://docs.python.org/3.4/library/base64.html

Is there an exact equivalent to 'btoa' in python?

chris
  • 1,649
  • 4
  • 24
  • 45

3 Answers3

25

Python's Base64:

import base64

encoded = base64.b64encode(b'Hello World!')
print(encoded)

# value of encoded is SGVsbG8gV29ybGQh

Javascript's btoa:

var str = "Hello World!";
var enc = window.btoa(str);

var res = enc;

// value of res is SGVsbG8gV29ybGQh

As you can see they both produce the same result.

blong
  • 2,778
  • 7
  • 40
  • 103
Harrison
  • 4,679
  • 7
  • 34
  • 56
  • While this works, it might be preferable to write it like [Shlomi Lachmish has](https://stackoverflow.com/a/56921526/320399) (explicitly encoding the text). Quoting another SO answer: "_To send text reliably you can first encode to bytes using a text encoding of your choice (for example UTF-8) and then afterwards Base64 encode the resulting binary data into a text string that is safe to send encoded as ASCII._" - https://stackoverflow.com/a/3538079/320399 . Also, see: https://stackoverflow.com/q/3470546 – blong Sep 29 '21 at 16:51
13

I tried the python code and got (with python3) TypeError: a bytes-like object is required, not 'str'

When I added the encode it seems to work

import base64

dataString = 'Hello World!'
dataBytes = dataString.encode("utf-8")
encoded = base64.b64encode(dataBytes)

print(encoded)  # res=> b'SGVsbG8gV29ybGQh'
Shlomi Lachmish
  • 433
  • 4
  • 13
0

if you are in django, usually a bit tricky with types.

import json
import base64


data = [{"a": 1, "b": 2}]

btoa = lambda x:base64.b64decode(x)
atob = lambda x:base64.b64encode(bytes(x, 'utf-8')).decode('utf-8')

encoded = atob(json.dumps(data))
print(encoded)
# W3siYSI6IDEsICJiIjogMn1d
print(type(encoded))
# <class 'str'>

decoded = json.loads(btoa(encoded))
print(decoded)
# [{'a': 1, 'b': 2}]
print(type(decoded))
# <class 'list'>
Weilory
  • 1,807
  • 9
  • 24