On Sun, 2007-05-06 at 11:39 -0400, David Clymer wrote: > I'm using pycrypto's AES module, and am attempting to automate the > padding of the plaintext (the size of the text to be encrypted must be a > multiple of 16). However, my padding scheme sometimes fails to calculate > the necessary padding correctly, and I'm not sure why. > > Using the text 'foo bar', it fails, but if I do 'foo bars' it works. > Randomized testing fails sometimes and not others. > > Any pointers as to what I might be doing wrong (code attached)?
Nevermind. After I walked away from it for a bit, the mistake was obvious. I was using the modulus of the text length by the block size directly, rather than the block size minus that number: --- /home/david/Desktop/test.py 2007-05-06 13:38:52.000000000 -0400 +++ test.py 2007-05-06 13:39:38.000000000 -0400 @@ -9,12 +9,12 @@ def __init__(self, text, key_phrase): key = SHA256.new(key_phrase) self.aes = AES.new(key.digest()) - #self.encrypted_text = self.aes.encrypt(self._pad(text)) + self.encrypted_text = self.aes.encrypt(self._pad(text)) def _unpad(self, txt): """Remove padding from the given text""" for x in xrange(len(txt) - self.aes.block_size,len(txt)): - if x == ord(txt[x]): + if len(txt[x:]) == ord(txt[x]): if txt[x-1:] + self._gen_pad(txt[x-1:]): return txt[:x] return txt @@ -25,7 +25,7 @@ def _gen_pad(self, txt): """Generate padding for the given plaintext""" - pad_len = (len(txt)) % self.aes.block_size + pad_len = self.aes.block_size - (len(txt) % self.aes.block_size) if pad_len > 0: return chr(pad_len) * pad_len return chr(self.aes.block_size) * self.aes.block_size -- gpg-key: http://www.zettazebra.com/files/key.gpg
signature.asc
Description: This is a digitally signed message part
-- http://mail.python.org/mailman/listinfo/python-list