【编程】Python3 使用自定义编码字符表解密Base64数据
前言
Python提供了“base64”模块用于编码、解码Base64数据。
但是并不是所有的Base64数据都会使用默认的字符表进行编码,所以这里对Python下实现自定义编码字符表解密Base64数据做一个简要记录。(关于Base64内部实现等相关内容可以参考这篇文章)
Python2.7
1 # -*- coding: utf-8 2 import base64 3 import string 4 5 STANDARD_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' 6 CUSTOM_ALPHABET = 'JXaYOjSNTet1dDrHsVlc0m5EknG7Ko6qibhFBuyzQUwxWCp4ZLf23gAvMR8PI9+/' 7 ENCODE_TRANS = string.maketrans(STANDARD_ALPHABET, CUSTOM_ALPHABET) 8 DECODE_TRANS = string.maketrans(CUSTOM_ALPHABET, STANDARD_ALPHABET) 9 10 def encode(input): 11 return base64.b64encode(input).translate(ENCODE_TRANS) 12 13 def decode(input): 14 return base64.b64decode(input.translate(DECODE_TRANS)) 15 16 enstr = encode("123") 17 print enstr #dcT2 18 19 destr = decode(enstr) 20 print destr #123
Python3.8
1 # -*- coding: utf-8 2 import base64 3 4 STANDARD_ALPHABET = b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' 5 CUSTOM_ALPHABET = b'JXaYOjSNTet1dDrHsVlc0m5EknG7Ko6qibhFBuyzQUwxWCp4ZLf23gAvMR8PI9+/' 6 ENCODE_TRANS = bytes.maketrans(STANDARD_ALPHABET, CUSTOM_ALPHABET) 7 DECODE_TRANS = bytes.maketrans(CUSTOM_ALPHABET, STANDARD_ALPHABET) 8 9 def encode(input): 10 return base64.b64encode(input).translate(ENCODE_TRANS) 11 12 def decode(input): 13 return base64.b64decode(input.translate(DECODE_TRANS)) 14 15 enstr = encode("123".encode()) 16 print(enstr.decode()) #dcT2 17 18 destr = decode(enstr) 19 print(destr.decode()) #123
参考链接:
https://bbs.khcloud.net/?thread-285.htm