In Python, using the Cryptography.Hazmat
module For AES, the output length of the encryption is not the a multiple of 16; am I implementing the encryption cipher wrong, and if so, what is wrong? The output length I recieve is 16 + len(input)
(16 as it is the length of the IV). Here is the code below:
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers.algorithms import AES
from cryptography.hazmat.primitives.ciphers.modes import CBC,OFB,CFB
class AES_Cipher:
def __init__(self,key):
self.key = key
def encrypt(self,plain_text):
initialization_vector = urandom(16)
cipher = Cipher(AES(self.key),OFB(initialization_vector),backend)
encryption_engine = cipher.encryptor()
return initialization_vector + encryption_engine.update(plain_text.encode("utf-8")) + encryption_engine.finalize()
def decrypt(self,cipher_text):
initialization_vector = cipher_text[:16]
cipher = Cipher(AES(self.key),OFB(initialization_vector),backend)
decryption_engine = cipher.decryptor()
return (decryption_engine.update(cipher_text[16:]) + decryption_engine.finalize()).decode("utf-8")
The cipher is called as so:
from hashlib import sha3_256
aes_key = sha3_256(b"Strong Encryption Key").digest()
aes_engine = AES_Cipher(aes_key)
aes_engine.encrypt("Hello World")
And this is the result:
b'\xc4I\xf2\xe5\xf4\xaeX\x96\xa5\xfe\xbd+\xde\x8ca\xd5\xdb\xad\x97S\x01\x81C\x9e\xd5\xd8@'
This is only 27 bytes long, compared to the expected 32 bytes. The 27 = 16 + len("Hello World"). Why is it not 32 bytes long? What is the code missing? Another thing; decryption works perfectly fine.
The length of 27 bytes is correct for OFB-mode.
The OFB-mode used in the Python-code turns a block cipher into a stream cipher. The difference between block cipher and stream cipher is described in more detail here. In particular, the length of the plaintext input can be arbitrary for a stream cipher, i.e. in contrast to a block cipher, the length does not have to be an integer multiple of the blocksize, so that no padding is required. The generated ciphertext has the same length as the plaintext.
In the current example, the plaintext Hello World, and therefore also the ciphertext, has a length of 11 bytes. Together with the IV, which has a length of 16 bytes, the total length is 27 bytes, which corresponds exactly to your result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With