python 实现 AES CBC模式加解密

AES加密方式有五种:ECB, CBC, CTR, CFB, OFB

从安全性角度推荐CBC加密方法,本文介绍了CBC,ECB两种加密方法的python实现

python 在 Windows下使用AES时要安装的是pycryptodome 模块   pip install pycryptodome 

python 在 Linux下使用AES时要安装的是pycrypto模块   pip install pycrypto 

CBC加密需要一个十六位的key(密钥)和一个十六位iv(偏移量)

1. 加密

加密时,明文首先与IV异或,然后将结果进行块加密,得到的输出就是密文,同时本次的输出密文作为下一个块加密的IV。 

2. 解密

解密时,先将密文的第一个块进行块解密,然后将结果与IV异或,就能得到明文,同时,本次解密的输入密文作为下一个块解密的IV。 

 

 

 3. 代码:

  

# -*- coding=utf-8-*-
from Crypto.Cipher import AES
import os
from Crypto import Random
import base64

"""
aes加密算法
padding : PKCS7
"""

class AESUtil:

    __BLOCK_SIZE_16 = BLOCK_SIZE_16 = AES.block_size

    @staticmethod
    def encryt(str, key, iv):
        cipher = AES.new(key, AES.MODE_CBC,iv)
        x = AESUtil.__BLOCK_SIZE_16 - (len(str) % AESUtil.__BLOCK_SIZE_16)
        if x != 0:
            str = str + chr(x)*x
        msg = cipher.encrypt(str)
        # msg = base64.urlsafe_b64encode(msg).replace('=', '')
        msg = base64.b64encode(msg)
        return msg

    @staticmethod
    def decrypt(enStr, key, iv):
        cipher = AES.new(key, AES.MODE_CBC, iv)
        # enStr += (len(enStr) % 4)*"="
        # decryptByts = base64.urlsafe_b64decode(enStr)
        decryptByts = base64.b64decode(enStr)
        msg = cipher.decrypt(decryptByts)
        paddingLen = ord(msg[len(msg)-1])
        return msg[0:-paddingLen]

if __name__ == "__main__":
    key = "1234567812345678"
    iv = "1234567812345678"
    res = AESUtil.encryt("123456", key, iv)
    print res # 2eDiseYiSX62qk/WS/ZDmg==
    print AESUtil.decrypt(res, key, iv) # 123456

 

 

 

 

 

 

 

  

 

posted @ 2019-08-28 08:25  淋哥  阅读(19414)  评论(1编辑  收藏  举报