title: Pycrypto AES-256 - How to Encrypt Texts with Large Bytes?
body: <p>I've been playing around with <code>pycrypto</code> and AES-256, and I've run into a bit of an issue with larger file sizes.</p>
  
  <p>For small strings, like "hello world!", the encryption/decryption works fine.</p>
  
  <p>But I would like to extend the encryption to text files of any reasonable size, but I've been running into this error:</p>
  
  <p><code>ValueError: Input strings must be a multiple of 16 in length</code></p>
  
  <p>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.</p>
  
  <p>My question is, how do I exactly go about doing that? Is there a built-in <code>pycrypto</code> 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.</p>
  
  <p>Here's how I pad/unpad the string to be encrypted (from <a href="https://gist.github.com/gustavohenrique/79cc95cc351d975a075f18a5c9f49319" rel="nofollow noreferrer">https://gist.github.com/gustavohenrique/79cc95cc351d975a075f18a5c9f49319</a>):</p>
  
  <pre><code>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:])]
  </code></pre>
  
  <p>And here's how the <code>Cipher</code> class is initialized: </p>
  
  <pre><code>def __init__(self, key):
      self.bs = 16
      self.cipher = AES.new(key, AES.MODE_ECB)
  </code></pre>
  
  <p>Encryption/Decryption:</p>
  
  <pre><code>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')
  </code></pre>