AES加密的数据块长度为128(16字节),长度不足需要填充。密码长度可以为16,24,32字节。
from Crypto.Cipher import AES
from Crypto import Random
bs = AES.block_size
pad = lambda s: s + (bs - (len(s) % bs)) * chr(bs - len(s) % bs)
unpad = lambda s: s[:-ord(s[len(s)-1:])]
class AESCipher:
def __init__(self, key):
self.key = key
def encrypt(self, rawdata):
rawdata = pad(rawdata)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return (iv + cipher.encrypt(rawdata))
def decrypt(self, enc):
iv = enc[:bs]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(enc[16:]))
def main():
key = Random.new().read(32)
cipher = AESCipher(key)
msg = 'message to be encrypted'
encrypted = cipher.encrypt(msg)
print 'encrypted data: ', encrypted
decrypted = cipher.decrypt(encrypted)
print 'decrypted data: ', decrypted
if __name__ == '__main__':
main()