Data Encoding Tutorials - Herong's Tutorial Examples - v5.23, by Herong Yang
Python Built-In Implementation of Base64
This section provides a test program for the default Python implementation of the Base64 encoding algorithm base64.b64encode() and base64.b64decode() methods.
The Base64 encoding algorithm bas been implemented in Python 3 language as 2 built-in methods:
To test these built-in functions, I wrote this simple testing program:
# Base64_Encode_Test.py
# Copyright (c) 2010 HerongYang.com. All Rights Reserved.
#
import base64
def test(theInput, theExpected):
inputBytes = theInput.encode();
encodedBytes = base64.b64encode(inputBytes)
decodedBytes = base64.b64decode(encodedBytes)
print(" Input : "+theInput)
print(" Encoded : "+encodedBytes.decode())
print(" Expected: "+theExpected)
print(" Decoded : "+decodedBytes.decode())
print("Test 1:")
theInput = "A"
theExpected = "QQ=="
test(theInput, theExpected)
print("Test 2:")
theInput = "AB"
theExpected = "QUI="
test(theInput, theExpected)
print("Test 3:")
theInput = "ABC"
theExpected = "QUJD"
test(theInput, theExpected)
print("Test 4:")
theInput = "The quick brown fox jumps over the lazy dog."
theExpected = \
"VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4="
test(theInput, theExpected)
Here is the test result:
herong> python3 Base64_Encode_Test.py Test 1: Input : A Encoded : QQ== Expected: QQ== Decoded : A Test 2: Input : AB Encoded : QUI= Expected: QUI= Decoded : AB Test 3: Input : ABC Encoded : QUJD Expected: QUJD Decoded : ABC Test 2: Input : The quick brown fox jumps over the lazy dog. Encoded : VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4= Expected: VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4= Decoded : The quick brown fox jumps over the lazy dog.
The result matches my expectation perfectly.
Table of Contents
►Base64 Encoding and Decoding Tools
Base64.Guru - Base64 Online Tool
Windows Command - "certutil -encode/-decode"
Java Built-In Implementation of Base64
Java Built-In Implementation of MIME Base64
►Python Built-In Implementation of Base64
Python Built-In Implementation of MIME Base64
PHP Built-In Implementation of Base64
PHP Built-In Implementation of MIME Base64
Perl Built-In Implementation of Base64
Perl Built-In Implementation of MIME Base64
Base64URL - URL Safe Base64 Encoding