Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

base64

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?

like image 668
chris Avatar asked Sep 04 '16 03:09

chris


People also ask

Why is BTOA deprecated?

btoa(): accepts a string where each character represents an 8bit byte. If you pass a string containing characters that cannot be represented in 8 bits, it will probably break. Probably that's why btoa is deprecated.

Does base64 come with Python?

Python 3 provides a base64 module that allows us to easily encode and decode information. We first convert the string into a bytes-like object. Once converted, we can use the base64 module to encode it.

What is base64 b64decode in Python?

b64decode() in Python. The base64. b4() function in Python decodes strings or byte-like objects encoded in base64 and returns the decoded bytes.

What is base64 b64encode in Python?

b64encode() in Python. With the help of base64. b64encode() method, we can encode the string into the binary form. Return : Return the encoded string.


2 Answers

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.

like image 120
Harrison Avatar answered Sep 19 '22 14:09

Harrison


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'
like image 36
Shlomi Lachmish Avatar answered Sep 21 '22 14:09

Shlomi Lachmish