Original address: http://www.pylist.com/topic/1435231261
-------------
The Base64 module is used for Base64 encoding and decoding. This type of encoding is common in e-mail. It can encode binary data that cannot be displayed as text as a text message that can be displayed. The encoded text size increases by 1/3.
The Base64 module really uses only 8 methods, namely encode, decode, encodestring, decodestring, B64encode, B64decode, Urlsafe_b64decode, Urlsafe_ B64encode. Their 8 can be 22 divided into 4 groups, encode, decode a group, specifically used to encode and decode files, but also to stringio the data to do codec; encodestring, decodestring a group, specifically used to encode and decode strings; A set of B64encode and b64decode that encode and decode strings and have a function to replace symbolic characters. This function is as follows: Since the Base64 encoded characters have three characters +/= In addition to the English alphabet and number, where = only to complement the whole number of characters after encoding 4 integers, while + and/in some cases need to be replaced, B64encode and B64decode It is the provision of such a function. As to what case + and/need to be replaced, the most common is when the URL is Base64 encoded. Urlsafe_b64encode and Urlsafe_b64decode, which is used specifically to decode URLs base64, is actually the previous set of functions that are called.
Python must be padded to the = number to be normal, otherwise it will be wrong no padding.
Python version:
def base64_url_decode (INP):
# Removes the = number from the URL transfer, so you need to fill the = number
import base64 return
Base64.urlsafe_b64decode (str (INP + ' = ' * (4-len (INP)% 4)))
def base64_url_encode (INP):
import base64 return
Base64.urlsafe_b64encode (str (INP)). Rstrip (' = ')
PHP Version:
function Base64url_encode ($data) {return
RTrim (STRTR (Base64_encode ($data), ' +/', '-_ '), ' = ');
}
function Base64url_decode ($data) {return
Base64_decode str_pad (STRTR ($data, '-_ ', ' +/'), strlen ($data)% 4, ' = ', Str_pad_right));
}