# Re: Crypto plaintext padding (SOLVED)

Discussion in 'Python' started by David Clymer, May 6, 2007.

1. ### David ClymerGuest

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())

"""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]):
return txt[:x]
return txt
@@ -25,7 +25,7 @@

"""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)
return chr(self.aes.block_size) * self.aes.block_size

--
gpg-key: http://www.zettazebra.com/files/key.gpg

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)

iD8DBQBGPhQI2XpGgG+SNaERAud2AKDKzu1ITIf+GsEEjEEJkxuiLmqDvgCgu88f
HECFlp/VYxFn/uMiuwlzeBc=
=3XCx
-----END PGP SIGNATURE-----

David Clymer, May 6, 2007