我已经搜索了很多关于完整加密解密的例子和我的要求。事实上,我有很多链接和示例,但是没有一个适合我的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填充,并且必须在Python3.4上运行。