zoukankan      html  css  js  c++  java
  • base64加密与解密

    原理

    转码过程例子:

    3*8=4*6
    内存1个字节占8位
    转前: s 1 3
    先转成ascii:对应 115 49 51
    2进制: 01110011 00110001 00110011
    6个一组(4组) 011100110011000100110011
    然后才有后面的 011100 110011 000100 110011
    然后计算机一个字节占8位,不够就自动补两个高位0了
    所以有了高位补0
    科学计算器输入 00011100 00110011 00000100 00110011
    得到 28 51 4 51
    查对下照表 c z E z

    python实现:

    import base64
    
    def base(string:str)->str:
        oldstr = ''
        newstr = []
        base = ''
        base64_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                       'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                       'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                       'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/']
        #把原始字符串转换为二进制,用bin转换后是0b开头的,所以把b替换了,首位补0补齐8位
        for i in string:
            oldstr += '{:08}'.format(int(str(bin(ord(i))).replace('0b', '')))
        #把转换好的二进制按照6位一组分好,最后一组不足6位的后面补0
        for j in range(0, len(oldstr), 6):
            newstr.append('{:<06}'.format(oldstr[j:j + 6]))
        #在base_list中找到对应的字符,拼接
        for l in range(len(newstr)):
            base += base64_list[int(newstr[l], 2)]
        #判断base字符结尾补几个‘=’
        if len(string) % 3 == 1:
            base += '=='
        elif len(string) % 3 == 2:
            base += '='
        return  base
    
    print(base("s13"))

    应用

    加密解密字符串:

    字符串必须先要组成bytes string

    import base64
    
    
    def solve(str):
        #转成bytes string
        bytesString = str.encode(encoding="utf-8")
        print(bytesString)
    
        #base64 编码
        encodestr = base64.b64encode(bytesString)
        print(encodestr)
        print(encodestr.decode())
    
        #解码
        decodestr = base64.b64decode(encodestr)
        print(decodestr.decode())
    
    
    if __name__ == '__main__':
        solve("ABC")

    加密解密图片:

    import base64    
    
    with open("nfsq.jpg","rb") as f:
        # b64encode是编码,b64decode是解码  
        base64_data = str(base64.b64encode(f.read()), encoding='utf-8')
        # base64.b64decode(base64data)  
        print(base64_data)

    html显示:

    <img src="data:image/jpg;base64,这里是base64的编码"/>

    打算写image2base64的程序,以交互式方式运行正确,写成脚本却报错“AttributeError: module 'base64' has no attribute 'b64decode'”。

    解决方法:我的程序名"base64.py"与包名冲突了,因此改名即可。

    参考链接:

    1. https://blog.csdn.net/XiangLanLee/article/details/84136519

    2. https://www.cnblogs.com/lanzhi/p/6468386.html

    3. https://baike.baidu.com/item/base64/8545775?fr=aladdin

  • 相关阅读:
    其他:Oracle并购sun之后的影响之我见
    60款很酷的 jQuery 幻灯片演示和下载
    分享35个高质量的 Apple 风格图标素材
    25个漂亮的旅游网站设计作品欣赏
    tomcat内存溢出总结
    一个非常强大完整的web表单验证程序
    java socket (回顾)
    jdbc 公共类(2)
    各大IT公司笔试真题汇总
    软件公司的岗位职责
  • 原文地址:https://www.cnblogs.com/lfri/p/11918578.html
Copyright © 2011-2022 走看看