alex/cryptography — pull request #65 by dstufft (2013-09-12 21:42:13+00:00)
Title: Add PKCS7 padding

#### Normal Operation

```python
from cryptography.primitives import padding
padder = padding.PKCS7(128)

def datamaker():
for c in b"11111111111111112222222222":
yield c

def datamaker2():
for c in [b"1111", b"1111", b"1111", b"1111", b"2222", b"2222", b"22"]:
yield c

def datamaker3():
for c in b"11111111111111112222222222\x06\x06\x06\x06\x06\x06":
yield c

def datamaker4():
for c in ['1111', '1111', '1111', '1111', '2222', '2222', '22\x06\x06', '\x06\x06\x06\x06']:
yield c

padded1 = padder.pad(b"1111") # '1111\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c'
padded2 = padder.pad(datamaker()) # '11111111111111112222222222\x06\x06\x06\x06\x06\x06'
padded3 = padder.iter_pad(datamaker2()) #

padded3 = b"".join(padded3) # '11111111111111112222222222\x06\x06\x06\x06\x06\x06'

unpadded1 = padder.unpad(padded1) # '1111'
unpadded2 = padder.unpad(datamaker3()) # '11111111111111112222222222'
unpadded3 = padder.iter_unpad(datamaker4()) #

unpadded3 = b"".join(unpadded3) # '11111111111111112222222222'
```

#### Error Conditions

```pycon
>>> from cryptography.primitives import padding
>>> padder = padding.PKCS7(128)
>>>
>>> padder.unpad(b"1111") # Too Few Bytes
Traceback (most recent call last):
File "", line 1, in
File "cryptography/primitives/padding.py", line 75, in unpad
return b"".join(self.iter_unpad(data))
File "cryptography/primitives/padding.py", line 60, in iter_unpad
raise ValueError("Invalid padding bytes")
ValueError: Invalid padding bytes
>>>
>>> padder.unpad(b"1111111111111111") # No padding characters at all
Traceback (most recent call last):
File "", line 1, in
File "cryptography/primitives/padding.py", line 75, in unpad
return b"".join(self.iter_unpad(data))
File "cryptography/primitives/padding.py", line 66, in iter_unpad
raise ValueError("Invalid padding bytes")
ValueError: Invalid padding bytes
>>>
>>> padder.unpad(b"111111111111111\x06") # Padding character but Invalid bytes
Traceback (most recent call last):
File "", line 1, in
File "cryptography/primitives/padding.py", line 75, in unpad
return b"".join(self.iter_unpad(data))
File "cryptography/primitives/padding.py", line 70, in iter_unpad
raise ValueError("Invalid padding bytes")
ValueError: Invalid padding bytes
```