base64编码-Python

# base64解码
class Decoder(object):
    tables = None 
    def __init__(self):
        self.__generateCodeTable()
    def __generateCodeTable(self):
        """
        解码的码表
        """
        codeTable = {}
        # ord(ss) 输出字符的ascii
        # chr(num) 输出数值对应的字符
        init_char = ord('A') - 1
        for i in range(26):
            init_char = chr(init_char + 1)
            codeTable[init_char] = i
        init_char = ord('a') - 1
        for j in range(26,52):
            init_char = chr(init_char + 1)
            codeTable[init_char] = j
        init_char = ord('0') -1
        for k in range(52,62):
            init_char = chr(init_char + 1)
            codeTable[init_char] = k
        codeTable['+'] = 62
        codeTable['/'] = 63
        self.tables = codeTable
    def __characterTo6Bin(self,msg):
        """
        将每个字符串转化为6位的二进制
        """
        result = ''
        for i in range(len(msg)):
            tep_str = ''
            tmp = bin(self.tables.get(msg[i]))[2:]
            if len(tmp) < 6 :
                num = 6 - len(tmp)
                for j in range(num):
                    tep_str += '0'
            tep_str += tmp
            result += tep_str
        return result
    def decode(self,msg):
        """
        解码base64编码的字符
        """
        index = msg.find('=')
        if index != -1:
            msg = msg[0:index]
        result = []
        str_bin = self.__characterTo6Bin(msg)
        length = len(str_bin)
        index = 0
        while index < length:
            if int(str_bin[index:index+8],2) > 127:
                tmp = str_bin[index:index+24]
                hex_str = str(hex(int(tmp,2)))
                hex_str = hex_str.replace('0x','')
                result.append(str(bytes.fromhex(hex_str),encoding='utf-8'))
                index += 24
            else:
                sub = str_bin[index:index+8]
                result.append(chr(int(sub,2)))
                index += 8
        if result[-1] == 0:
            result = result[0:-1]
        origin = ""
        for key in result:
            origin += key
        return origin.replace('\x00','')
decode = Decoder()
decode.decode('5Lit5Zu9')

新闻名称:base64编码-Python
文章位置:http://scjbc.cn/article/jjjgde.html

其他资讯