19

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?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
chris
  • 1,869
  • 4
  • 29
  • 52

3 Answers3

27

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,815
  • 8
  • 44
  • 110
Harrison
  • 5,095
  • 7
  • 40
  • 60
  • 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
14

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
  • 541
  • 5
  • 14
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
  • 2,621
  • 19
  • 35
  • 1
    Per [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/btoa), these function names are switched. "The btoa() method creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data)." And [atob](https://developer.mozilla.org/en-US/docs/Web/API/atob) "The atob() function decodes a string of data which has been encoded using Base64 encoding." So it might be better if the functions were named `btoa` for encoding and `atob` for decoding. – elgreg Jan 30 '23 at 17:08