zoukankan      html  css  js  c++  java
  • python 实现AES加密和解密

    参考 https://blog.csdn.net/zhchs2012/article/details/79032656

    AES加密算法是一种对称加密算法, 他有一个密匙, 即用来加密, 也用来解密

    import base64
    from Crypto.Cipher import AES
    # 密钥(key), 密斯偏移量(iv) CBC模式加密
    
    def AES_Encrypt(key, data):
        vi = '0102030405060708'
        pad = lambda s: s + (16 - len(s)%16) * chr(16 - len(s)%16)
        data = pad(data)
        # 字符串补位
        cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
        encryptedbytes = cipher.encrypt(data.encode('utf8'))
        # 加密后得到的是bytes类型的数据
        encodestrs = base64.b64encode(encryptedbytes)
        # 使用Base64进行编码,返回byte字符串
        enctext = encodestrs.decode('utf8')
        # 对byte字符串按utf-8进行解码
        return enctext
    
    
    def AES_Decrypt(key, data):
        vi = '0102030405060708'
        data = data.encode('utf8')
        encodebytes = base64.decodebytes(data)
        # 将加密数据转换位bytes类型数据
        cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
        text_decrypted = cipher.decrypt(encodebytes)
        unpad = lambda s: s[0:-s[-1]]
        text_decrypted = unpad(text_decrypted)
        # 去补位
        text_decrypted = text_decrypted.decode('utf8')
        return text_decrypted
    
    
    key = '0CoJUm6Qyw8W8jud'
    data = 'sdadsdsdsfd'
    AES_Encrypt(key, data)
    enctext = AES_Encrypt(key, data)
    print(enctext)
    text_decrypted = AES_Decrypt(key, enctext)
    print(text_decrypted)
    
    hBXLrMkpkBpDFsf9xSRGQQ==
    sdadsdsdsfd
    

      

  • 相关阅读:
    使用idea15搭建基于maven的springmvc-mybatis框架
    git本地提交到远程仓库命令
    jsp表格数据导出到Execl
    FreeMarker标签介绍
    FreeMarker常用语法
    mybatis批量删除
    git之https或http方式设置记住用户名和密码的方法
    INPUT只能输入数字
    mysql 日期格式化
    cygwin配置git
  • 原文地址:https://www.cnblogs.com/frank-shen/p/10281708.html
Copyright © 2011-2022 走看看