My question is how to use CFB mode in pycrypto? My problem is the module doesn't accept the arbitrary length of IV and key.
>>> from Crypto.Cipher import AES
>>> aes = AES.new('123456', AES.MODE_CFB, '12345678')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/AES.py", line 94, in new
return AESCipher(key, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/AES.py", line 59, in __init__
blockalgo.BlockAlgo.__init__(self, _AES, key, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/blockalgo.py", line 141, in __init__
self._cipher = factory.new(key, *args, **kwargs)
ValueError: IV must be 16 bytes long
Next:
>>> aes = AES.new('123456', AES.MODE_CFB, '1234567890ABCDEF')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/AES.py", line 94, in new
return AESCipher(key, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/AES.py", line 59, in __init__
blockalgo.BlockAlgo.__init__(self, _AES, key, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/blockalgo.py", line 141, in __init__
self._cipher = factory.new(key, *args, **kwargs)
ValueError: AES key must be either 16, 24, or 32 bytes long
As to my understanding CFB mode should accept arbitrary IV and key lengths, or am I wrong?
AES is specified for key sizes of 128, 192 and 256 bit as well as a block size of 128 bit. The IV size for at least CBC and CFB mode should equal the block size. Everything beyond that is not part of the specification and therefore not interoperable with other implementations.
You need to use a long enough key and IV. If you want to use a password instead of a key, use hashing to derive one. Passwords have generally much lower entropy than random keys, so you need to strong (meaning slow) key derivation function that transforms the given password to a key. This will make it hard for attackers to brute-force passwords at a high rate. A good key derivation function is PBKDF2 which is provided by PyCrypto. The default parameters are ok, but you might want to increase the iteration count to 10,000.
The IV should be generated randomly during encryption, but it doesn't have to be kept secret. Usually the IV is prepended to the ciphertext before sending it. Since the size of the IV is known, it can be easily sliced off during decryption and used.