使用PKCS#7填充在Python 3中进行AES-CBC 128,192和256加密解密

时间:2016-09-23 05:17:15

标签: python aes pycrypto pkcs#7 cbc-mode

我已根据我的要求搜索了很多关于完整加密解密示例的内容。事实上,我有很多链接和示例,但是对于我来说,AES-192-CBC模式和AES-256-CBC都没有。

我有以下示例,它应该适用于所有类型,但它仅适用于AES-128-CBC模式。我是Python的新手。任何人都可以在我错的地方帮助我吗?

我在Windows上使用Python 3.4,我无法转向Python 2.7。

import base64
from Crypto.Cipher import AES

class AESCipher:
    class InvalidBlockSizeError(Exception):
        """Raised for invalid block sizes"""
        pass

    def __init__(self, key, block_size=16):
        if block_size < 2 or block_size > 255:
            raise AESCipher.InvalidBlockSizeError('The block size must be between 2 and 255, inclusive')
        self.block_size = block_size
        self.key = key
        self.iv = bytes(key[0:16], 'utf-8')
        print(self.key)
        print(key[0:16])

    def __pad(self, text):
        text_length = len(text)
        amount_to_pad = self.block_size - (text_length % self.block_size)
        if amount_to_pad == 0:
            amount_to_pad = self.block_size
        self.pad = chr(amount_to_pad)
        return text + self.pad * amount_to_pad

    def __unpad(self, text):
        #pad = ord(text[-1])
        #return text[:-pad]
        text = text.rstrip(self.pad)
        return text

    def encrypt( self, raw ):
        raw = self.__pad(raw)
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        return base64.b64encode(cipher.encrypt(raw)) 

    def decrypt( self, enc ):
        enc = base64.b64decode(enc)
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv )
        return self.__unpad(cipher.decrypt(enc).decode("utf-8"))

e = AESCipher('1234567812345678', 16)
#e = AESCipher('123456781234567812345678', 24)
#e = AESCipher('12345678123456781234567812345678', 32)
secret_data = "hi"
enc_str = e.encrypt(secret_data)
print('enc_str: ' + enc_str.decode())
dec_str = e.decrypt(enc_str)
print('dec str: ' + dec_str)

虽然此代码使用192和256位加密对数据进行加密并成功解密,但我的其他.Net和Ruby应用程序只能解密使用128加密加密的数据。

注意.Net和Ruby应用程序相互成功测试,并使用所有加密类型的在线加密工具。

请注意,我的应用程序需要AES-CBC模式和PKCS#7填充,并且必须在Python 3.4上运行。

1 个答案:

答案 0 :(得分:2)

通过填充16个字节的任何加密类型使其工作。为此,我使用AES.block_size,默认情况下为AES。

import base64
from Crypto.Cipher import AES

class AESCipher:
    class InvalidBlockSizeError(Exception):
        """Raised for invalid block sizes"""
        pass

    def __init__(self, key):
        self.key = key
        self.iv = bytes(key[0:16], 'utf-8')
        print(self.key)
        print(key[0:16])

    def __pad(self, text):
        text_length = len(text)
        amount_to_pad = AES.block_size - (text_length % AES.block_size)
        if amount_to_pad == 0:
            amount_to_pad = AES.block_size
        pad = chr(amount_to_pad)
        return text + pad * amount_to_pad

    def __unpad(self, text):
        pad = ord(text[-1])
        return text[:-pad]

    def encrypt( self, raw ):
        raw = self.__pad(raw)
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        return base64.b64encode(cipher.encrypt(raw)) 

    def decrypt( self, enc ):
        enc = base64.b64decode(enc)
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv )
        return self.__unpad(cipher.decrypt(enc).decode("utf-8"))

e = AESCipher('1234567812345678', 16)
#e = AESCipher('123456781234567812345678', 24)
#e = AESCipher('12345678123456781234567812345678', 32)
secret_data = "hi"
enc_str = e.encrypt(secret_data)
print('enc_str: ' + enc_str.decode())
dec_str = e.decrypt(enc_str)
print('dec str: ' + dec_str)