Take the 2-minute tour ×

I just found pycrypto today, and I've been working on my AES encryption class. Unfortunately it only half-works. self.h.md5 outputs md5 hash in hex format, and is 32byte. This is the output. It seems to decrypt the message, but it puts random characters after decryption, in this case \n\n\n... I think I have a problem with block size of self.data, anyone know how to fix this?

Jans-MacBook-Pro:test2 jan$ ../../bin/python3 data.py b'RLfGmn5jf5WTJphnmW0hXG7IaIYcCRpjaTTqwXR6yiJCUytnDib+GQYlFORm+jIctest 1 2 3 4 5 endtest\n\n\n\n\n\n\n\n\n\n'

from Crypto.Cipher import AES
from base64 import b64encode, b64decode
from os import urandom

class Encryption():
    def __init__(self):
        self.h = Hash()

    def values(self, data, key):
        self.data = data
        self.key = key
        self.mode = AES.MODE_CBC
        self.iv = urandom(16)
        if not self.key:
            self.key = Cfg_Encrypt_Key
        self.key = self.h.md5(self.key, True)

    def encrypt(self, data, key):
        self.values(data, key)
        return b64encode(self.iv + AES.new(self.key, self.mode, self.iv).encrypt(self.data))

    def decrypt(self, data, key):
        self.values(data, key)
        self.iv = b64decode(self.data)[:16]
        return AES.new(self.key, self.mode, self.iv).decrypt(b64decode(self.data)[16:])
share|improve this question
add comment

2 Answers

up vote 12 down vote accepted

To be honest, the characters "\n\n\n\n\n\n\n\n\n\n" don't look that random to me. ;-)

You are using AES in CBC mode. That requires length of plaintext and ciphertext to be always a multiple of 16 bytes. With the code you show, you should actually see an exception being raised when data passed to encrypt() does not fulfill such condition. It looks like you added enough new line characters ('\n' to whatever the input is until the plaintext happened to be aligned.

Apart from that, there are two common ways to solve the alignment issue:

  1. Switch from CBC (AES.MODE_CBC) to CFB (AES.MODE_CFB). With the default segment_size used by PyCrypto, you will not have any restriction on plaintext and ciphertext lengths.

  2. Keep CBC and use a padding scheme like PKCS#7, that is:

    • before encrypting a plaintext of X bytes, append to the back as many bytes you need to to reach the next 16 byte boundary. All padding bytes have the same value: the number of bytes that you are adding:

      length = 16 - (len(data) % 16)
      data += bytes([length])*length

      That's Python 3 style. In Python 2, you would have:

      length = 16 - (len(data) % 16)
      data += chr(length)*length
    • after decrypting, remove from the back of the plaintext as many bytes as indicated by padding:

      data = data[:-data[-1]]

Even though I understand in your case it is just a class exercise, I would like to point out that it is insecure to send data without any form of authentication (e.g. a MAC).

share|improve this answer
Oh wow, your padding solution is really neat. I went with approach where I added $^End#Something^$ to end of body that is to be encrypted, and than also bunch of # signs till whole body is multiple of 16. Than when Im done decrypting, I rstrip #'s and remove my end string. Anyway, what do you mean with sending data without form of authentication? –  Jan Netherdrake Jan 8 '13 at 4:51
If you mean hmac signing, yes Ive builtin sha256 hmac signing into my encrypt function. Anyway, out of curiosity I tried your padding solution, and it doesn't work. I fiddled with it to the point I got padding to work, but unpadding just deletes everything. def pad2(self, data): if not isinstance(data, bytes): self.data = bytes(self.data, 'utf-8') size = (self.blockSize - len(self.data)) % self.blockSize self.data += bytes(size, 'ascii') return self.data def unpad2(self, data): return data[:-data[-1]] –  Jan Netherdrake Jan 8 '13 at 5:24
Yes, HMAC is OK. It's important to have it because serious attacks exist on the padding part (padding oracle attack). In Python/PyCrypto, all data you encrypt must always be a binary string, not a text string. That was not important in Python2, but in Python3 they are two different things now. –  SquareRootOfTwentyThree Jan 8 '13 at 7:52
And I fixed the code snipped too... –  SquareRootOfTwentyThree Jan 8 '13 at 9:04
Because plaintexts and ciphertexts are not text strings. They must be a sequence of exactly 16 bytes. If take a text strings, I can encode it into bytes in several different ways (UTF-8, UTF-16, ASCII, etc). That distinction is very important in Python3. –  SquareRootOfTwentyThree Jan 17 '13 at 6:44
show 1 more comment

AES.new().encrypt() and .decrypt() take as both input and output strings whose length is a multiple of 16. You have to fix it in one way or another. For example you can store the real length at the start, and use that to truncate the decrypted string.

Note also that while it's the only restriction for AES, other modules (notably in Crypto.PublicKey) have additional restrictions that comes from their mathematical implementation and that shouldn't (in my opinion) be visible to the end user, but are. For example Crypto.PublicKey.ElGamal will encrypt any short string, but if it starts with null characters, they are lost upon decryption.

share|improve this answer
Aha, I see. I've read somewhere that the length has to do something with 16byte multiplier, didn't really focus it. Thanks for making it clear. I suppose I will implant some sort of ending identifier in self.data and fill remaining to 16 multiplier with garbage data, than when decrypting delete everything from and including ending identifier on. This way I will eliminate the need to store additional length value. –  Jan Netherdrake Jan 6 '13 at 15:48
add comment

Your Answer


