To include the base64 module in your script, you must import it first:
import base64
The base64 encode and decode functions both require a bytes-like object. To get our string into bytes, we must encode it using Python's built in encode function. Most commonly, the UTF-8
encoding is used, however a full list of these standard encodings (including languages with different characters) can be found here in the official Python Documentation. Below is an example of encoding a string into bytes:
s = "Hello World!"
b = s.encode("UTF-8")
The output of the last line would be:
b'Hello World!'
The b
prefix is used to denote the value is a bytes object.
To Base64 encode these bytes, we use the base64.b64encode()
function:
import base64
s = "Hello World!"
b = s.encode("UTF-8")
e = base64.b64encode(b)
print(e)
That code would output the following:
b'SGVsbG8gV29ybGQh'
which is still in the bytes object. To get a string out of these bytes, we can use Python's decode()
method with the UTF-8
encoding:
import base64
s = "Hello World!"
b = s.encode("UTF-8")
e = base64.b64encode(b)
s1 = e.decode("UTF-8")
print(s1)
The output would then be:
SGVsbG8gV29ybGQh
If we wanted to encode the string and then decode we could use the base64.b64decode()
method:
import base64
# Creating a string
s = "Hello World!"
# Encoding the string into bytes
b = s.encode("UTF-8")
# Base64 Encode the bytes
e = base64.b64encode(b)
# Decoding the Base64 bytes to string
s1 = e.decode("UTF-8")
# Printing Base64 encoded string
print("Base64 Encoded:", s1)
# Encoding the Base64 encoded string into bytes
b1 = s1.encode("UTF-8")
# Decoding the Base64 bytes
d = base64.b64decode(b1)
# Decoding the bytes to string
s2 = d.decode("UTF-8")
print(s2)
As you may have expected, the output would be the original string:
Base64 Encoded: SGVsbG8gV29ybGQh
Hello World!