0

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')
LeetCoder
  • 563
  • 1
  • 5
  • 17
  • Possible duplicate of [Python Encrypting with PyCrypto AES](https://stackoverflow.com/questions/14179784/python-encrypting-with-pycrypto-aes) – Giacomo Alzetta Aug 21 '18 at 07:32
  • It looks like that solution works for Python2, but not Python3. I can create the cipher using AES CBC, but I cannot for the life of me find out how to chunk long texts. – LeetCoder Aug 21 '18 at 11:30
  • Data being a multiples of 16 bytes does not mean you nead to chunk them. It means that data needs to have a length that is divisible by 16 .. eg 48 bytes would be a multiplum of 16 (3 times 16), but 47 would not. Basically your data needs to be padded to a multiplum of 16, and for that you use padding modes as indicated by one of the other comments. – Ebbe M. Pedersen Aug 21 '18 at 12:59

0 Answers0