美文网首页
python实现的base64encode

python实现的base64encode

作者: Harvest | 来源:发表于2019-05-05 21:13 被阅读0次

    关于Base64编码原理,这里推荐一篇很好的博客一篇文章彻底弄懂Base64编码原理

    然后以下是我的python实现:

    # coding:utf-8
    import base64
    
    ALPHA=[chr(i) for i in range(65,91)]
    alpha=[chr(i) for i in range(97,123)]
    digit = [str(i) for i in range(0,10)]
    ALPHA.extend(alpha)
    ALPHA.extend(digit)
    ALPHA.append('+')
    ALPHA.append("/")
    table = {}
    # 构建映射表
    for i,v in enumerate(ALPHA):
        table[i]=v
    
    class Myencoder():
        def __init__(self,yard=8,table={}):
            self.table=table
            self.yard=yard
        def baseEncode(self,target):
            if not isinstance(target,bytes) and not isinstance(target,str):
                raise TypeError('不是可以编码的类型')
            result = ""
            for i in range(0,len(target),3):
                tlist = ""
                current = target[i:i+3]
                for curr in current:
                    tlist+=self.bianma(curr)
                tr = []
                for i in range(len(tlist) - 6, -1, -6):
                    nowaday = tlist[i:i + 6]
                    tr.append(nowaday)
                tr.reverse()
                tr = [int(v.zfill(8),2) for v in tr]
                tr = [self.table[key] for key in tr]
                if len(current) == 3:
                    pass
                elif len(current) == 2:
                    tr.append("=")
                elif len(current) == 1:
                    tr.append('=')
                    tr.append('=')
                result += ''.join(tr)
            return result
    
        def bianma(self,ma):
            otar = ord(ma)
            btar = bin(otar)
            btar = btar[2:]
            btar=btar.zfill(8)
            return btar
    myencoder = Myencoder(table=table)
    print(myencoder.baseEncode('sfimsi'))
    print(base64.b64encode(b'sfimsi'))
    

    相关文章

      网友评论

          本文标题:python实现的base64encode

          本文链接:https://www.haomeiwen.com/subject/cvjkoqtx.html