Does python have an equivalent to Javascript's 'btoa'

21.5k Views Asked by At

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?

4

There are 4 best solutions below

1
Harrison On BEST ANSWER

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.

1
Shlomi Lachmish On

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'
1
Weilory On

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'>
0
LazyDeus On

I studied the btoa source code in WebKit, it uses Latin-1 encoding instead of UTF-8. After using the Latin-1 encoding, everything worked as it should

from base64 import b64encode, b64decode


def btoa(value: str) -> str:
    # btoa source: https://github.com/WebKit/WebKit/blob/fcd2b898ec08eb8b922ff1a60adda7436a9e71de/Source/JavaScriptCore/jsc.cpp#L1419
    binary = value.encode("latin-1")
    return b64encode(binary).decode()


def atob(value: str) -> str:
    binary = b64decode(value.encode())
    return binary.decode("latin-1")

I created a library for convenience:

pip install btoa

from btoa import btoa, atob

assert btoa("Hello World!") == "SGVsbG8gV29ybGQh"
assert atob("SGVsbG8gV29ybGQh") == "Hello World!"