I've been playing around with pycrypto
and AES-256, and I've run into a bit of an issue with larger file sizes.
For small strings, like "hello world!", the encryption/decryption works fine.
But I would like to extend the encryption to text files of any reasonable size, but I've been running into this error:
ValueError: Input strings must be a multiple of 16 in length
I understand that this is because AES-256 is a block cipher, and so the texts need to be in multiples of 16 bytes, and if bytes are big, then I need to chunk them.
My question is, how do I exactly go about doing that? Is there a built-in pycrypto
method for it? I'm quite new to cryptography, so I don't think I'd be able to write a chunking method on my own.
Here's how I pad/unpad the string to be encrypted (from https://gist.github.com/gustavohenrique/79cc95cc351d975a075f18a5c9f49319):
def pad(self, s):
return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
def unpad(self, s):
return s[:-ord(s[len(s)-1:])]
And here's how the Cipher
class is initialized:
def __init__(self, key):
self.bs = 16
self.cipher = AES.new(key, AES.MODE_ECB)
Encryption/Decryption:
def encrypt(self, raw):
raw = self._pad(raw)
encrypted = self.cipher.encrypt(raw)
encoded = base64.b64encode(encrypted)
return str(encoded, 'utf-8')
def decrypt(self, raw):
decoded = base64.b64decode(raw)
decrypted = self.cipher.decrypt(decoded)
return str(self._unpad(decrypted), 'utf-8')