Python的base64模块


Python的base64模块是用来作base64编解码的。这种编码方式在电子邮件中是很常见的。它可以把不能作为文本显示的二进制数据编码为可显示的文本信息。编码后的文本大小会增大1/3。

闲话不多说,base64模块真正用的上的方法只有8个,分别是encode, decode, encodestring, decodestring, b64encode, b64decode, urlsafe_b64decode, urlsafe_b64encode。他们8个可以两两分为4组:

一、encode和decode一组,专门用来编码和解码文件的,也可以对StringIO里的数据做编解码;

二、encodestring和decodestring一组,专门用来编码和解码字符串

三、b64encode和b64decode一组,用来编码和解码字符串,并且有一个替换符号字符的功能。这个功能是这样的:因为base64编码后的字符除了英文字母和数字外还有三个字符“+ / =”,其中=只是为了补全编码后的字符数为4的整数,而+和/在一些情况下需要被替换掉,b64encode和b64decode正是提供了这样的功能。至于什么情况下+和/需要被替换,最常见的就是对url进行base64编码的时候;

四、urlsafe_b64encode和urlsafe_b64decode一组,这个就是用来专门对url进行base64编解码的,实际上也是调用的前一组函数。

下面看看例子:

#-*- encoding:utf-8 -*-
import base64
import StringIO

a = "this is a test"
b = base64.encodestring(a) # 对字符串编码
print b
print base64.decodestring(b) # 对字符串解码

c = StringIO.StringIO()
c.write(a)
d = StringIO.StringIO()
e = StringIO.StringIO()
c.seek(0)
base64.encode(c, d) # 对StringIO内的数据进行编码
print d.getvalue()
d.seek(0)
base64.decode(d, e) # 对StringIO内的数据进行解码
print e.getvalue()

a = "this is a +test"
b = base64.urlsafe_b64encode(a) # 进行url的字符串编码
print b
print base64.urlsafe_b64decode(b)

上面的encode函数和decode函数的参数其实还可以是文件对象的,那的像这样:

f1 = open('aaa.txt', 'r')
f2 = open('bbb.txt', 'w')
base64.encode(f1, f2)
f1.close()
f2.close()

用IPython进行查看的情况如下:

1.encode和decode
In [2]: base64.encode??
Type:        function
String form: <function encode at 0x02871770>
File:        c:python27libbase64.py
Definition:  base64.encode(input, output)
Source:
def encode(input, output):
    """Encode a file."""
    while True:
        s = input.read(MAXBINSIZE)
        if not s:
            break
        while len(s) < MAXBINSIZE:
            ns = input.read(MAXBINSIZE-len(s))
            if not ns:
                break
            s += ns
        line = binascii.b2a_base64(s)
        output.write(line)
2.encodestring和decodestring
In [3]: base64.encodestring??
Type:        function
String form: <function encodestring at 0x028717F0>
File:        c:python27libbase64.py
Definition:  base64.encodestring(s)
Source:
def encodestring(s):
    """Encode a string into multiple lines of base-64 data."""
    pieces = []
    for i in range(0, len(s), MAXBINSIZE):
        chunk = s[i : i + MAXBINSIZE]
        pieces.append(binascii.b2a_base64(chunk))
    return "".join(pieces)
3.b64encode和b64decode
In [4]: base64.b64encode??
Type:        function
String form: <function b64encode at 0x028714F0>
File:        c:python27libbase64.py
Definition:  base64.b64encode(s, altchars=None)
Source:
def b64encode(s, altchars=None):
    """Encode a string using Base64.

    s is the string to encode.  Optional altchars must be a string of at least
    length 2 (additional characters are ignored) which specifies an
    alternative alphabet for the '+' and '/' characters.  This allows an
    application to e.g. generate url or filesystem safe Base64 strings.

    The encoded string is returned.
    """
    # Strip off the trailing newline
    encoded = binascii.b2a_base64(s)[:-1]
    if altchars is not None:
        return _translate(encoded, {'+': altchars[0], '/': altchars[1]})
    return encoded
4.urlsafe_b64encode和urlsafe_b64decode(调用的也是上面的b64encode和b64decode函数)
In [6]: base64.urlsafe_b64encode??
Type:        function
String form: <function urlsafe_b64encode at 0x028715F0>
File:        c:python27libbase64.py
Definition:  base64.urlsafe_b64encode(s)
Source:
def urlsafe_b64encode(s):
    """Encode a string using a url-safe Base64 alphabet.

    s is the string to encode.  The encoded string is returned.  The alphabet
    uses '-' instead of '+' and '_' instead of '/'.
    """
    return b64encode(s, '-_')

 

参考链接:
,

《 “Python的base64模块” 》 有 2 条评论

  1. java-判断字符串是否经过base64编码
    https://blog.csdn.net/u010637238/article/details/103615589
    `
    字符串长度是4的倍数
    =只会出现在字符串最后,可能没有或者一个等号或者两个等号
    字符串只可能包含A-Z,a-z,0-9,+,/,=字符

    对于某些字符串可能符合base64编码特征,但是却不是base64编码格式,进行进一步判断,如果解码后含有乱码(即Ascii码不在32~126),说明虽然符合base64编码特征,但是不是base64编码,那么保留原始字符串
    `
    如何识别是否是base64编码加密
    https://blog.csdn.net/qq_46541895/article/details/112503930

    如何判断一个字符串是否经过base64加密过?
    https://www.zhihu.com/question/20304015

    如何判断一个字符串是否经过base64加密过?_判断是否是base64 java-程序员宅基地
    https://www.cxyzjd.com/article/Xionghuimin/103208425

    How do you decode Base64 data in Python?
    https://stackoverflow.com/questions/3470546/how-do-you-decode-base64-data-in-python

    How do you decode Base64 data in Python?
    https://stackoverflow.com/questions/3470546/how-do-you-decode-base64-data-in-python
    `
    # Python 3 (and 2)
    import base64
    a = ‘eW91ciB0ZXh0’
    base64.b64decode(a)
    `

    base64 — Base16, Base32, Base64, Base85 Data Encodings
    https://docs.python.org/3/library/base64.html

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注