pyca / cryptography

cryptography is a package designed to expose cryptographic primitives and recipes to Python developers.
https://cryptography.io
Other
6.59k stars 1.51k forks source link

The length of the provided data is not a multiple of the block length #3387

Closed xuanzhui closed 7 years ago

xuanzhui commented 7 years ago

When I try to encrypt a message that less than 16bytes, I get below error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/cryptography/hazmat/primitives/ciphers/base.py", line 142, in finalize
    data = self._ctx.finalize()
  File "/usr/local/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/ciphers.py", line 142, in finalize
    "The length of the provided data is not a multiple of "
ValueError: The length of the provided data is not a multiple of the block length.

The full code is:

>>> key=b'LYztg7Pshp5Gaos0'
>>> iv=b'O3wVdpjORNU0O6Ce'
>>> content=b'python'
>>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
>>> encryptor = cipher.encryptor()
>>> ct = encryptor.update(content) + encryptor.finalize()

which is almost the same from the doc.

Why not auto pad using PKCS#7?

reaperhulk commented 7 years ago

The hazmat module contains primitives designed to be composable. Not every consumer wants the same padding and some use cases don't want it at all. You can trivially add padding via the padding module but as always unless you're building against a legacy spec or doing bulk encryption I strongly suggest just using fernet.