base64

今天在跟第三方对接的时候, 意外发现base64编码在Python中有着两种不一样的表述:

In [1]: import base64

In [2]: text = "3\x81uIj\xbb\x08\x15\x04\xbaW\xc5\x16\xcdlyZ`C\xd9\xd5\xf0|\xa8\x01%\x8cWY\x1c\x1a~\xb8m\xa1\x03\xd5\x8e\x8f\xfb\xd35\xa6\x99_\x9c\xb0\xfc\xbe\xfd\x04\xc4\x8dj\x97\xc0\x1doM\xdf\xc5]\xd2\xfa\xe1\x88P\xde&\x82\x06\xcf}\xfe\xe89FW\xc4\xfd\x12\xa99\n\x80\xe7a\x93\xa0\x92F\x96{\xaf\x0bP\x8a\x18c\x9b\x02\xde\xba\xcd\xf3\xc5w2\xf5\xd7\x93\xc9\xbcFd\xa7\x87\x98\xe1U\xfd\x93\x17\xdf\xc7\r6\xf8\xe8\x99\xbc\x18X&\xd5~G\x07\x07\x03>\xb51\x82\x83\xca\xf2\xdb\xa1D\xd5\x04\xce\x8a\x89v'\xfdd\xf9'z\xc4\xdcw>\x7f\x82\x0c\x8f\xa5_\x88\xf5Z\xe9\xa2\x18UB\x83\xfc9\x05Q\xb1\x87\xa1\xb9+\xc4\x07\xd1xEq\x0e\xde\xfe\xad"

In [3]: print base64.b64encode(text)
M4F1SWq7CBUEulfFFs1seVpgQ9nV8HyoASWMV1kcGn64baED1Y6P+9M1pplfnLD8vv0ExI1ql8Adb03fxV3S+uGIUN4mggbPff7oOUZXxP0SqTkKgOdhk6CSRpZ7rwtQihhjmwLeus3zxXcy9deTybxGZKeHmOFV/ZMX38cNNvjombwYWCbVfkcHBwM+tTGCg8ry26FE1QTOiol2J/1k+Sd6xNx3Pn+CDI+lX4j1WumiGFVCg/w5BVGxh6G5K8QH0XhFcQ7e/q0=

In [4]: print base64.encodestring(text)
M4F1SWq7CBUEulfFFs1seVpgQ9nV8HyoASWMV1kcGn64baED1Y6P+9M1pplfnLD8vv0ExI1ql8Ad
b03fxV3S+uGIUN4mggbPff7oOUZXxP0SqTkKgOdhk6CSRpZ7rwtQihhjmwLeus3zxXcy9deTybxG
ZKeHmOFV/ZMX38cNNvjombwYWCbVfkcHBwM+tTGCg8ry26FE1QTOiol2J/1k+Sd6xNx3Pn+CDI+l
X4j1WumiGFVCg/w5BVGxh6G5K8QH0XhFcQ7e/q0=

前者对方接受不能. 记之以作备忘.

Python Doc:

base64.b64encode = 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.

base64.encodestring = encodestring(s)

    Encode a string into multiple lines of base-64 data.

具体的 多行 是由 Email 的 MIME 协议规定的: 每76个字符就换行.


另, Python的加密模块 M2Crypto 实在是累感不爱, 没文档搞屁啊!