Search code examples
pythonencryptiondespycrypto

DES.MODE_OFB doesn't recover the plaintext


Consider the two codes below (based on http://pythonhosted.org//pycrypto/):

1) DES.MODE_ECB

from Crypto.Cipher import DES    
from Crypto import Random    
key = b'Eight888'    
cipher = DES.new(key, DES.MODE_ECB)    
plaintext = b'sona si latine loqueris '    
msg = cipher.encrypt(plaintext)    
msgback= cipher.decrypt(msg)

2) DES.MODE_OFB

from Crypto.Cipher import DES
from Crypto import Random
key = b'Eight888'
iv = Random.new().read(DES.block_size)
cipher = DES.new(key, DES.MODE_OFB, iv)
plaintext = b'sona si latine loqueris '
msg = iv + cipher.encrypt(plaintext)
msgback= cipher.decrypt(msg)

Why is that code 1) recovers the original plaintext and 2) doesn't?


Solution

  • You have to slice off the IV before decrypting, because it is not part of the ciphertext.

    decCipher = DES.new(key, DES.MODE_OFB, msg[:DES.block_size])
    msgback = decCipher.decrypt(msg[DES.block_size:])
    

    Unlike CBC where decrypting with the IV recovers at least a part of the plaintext, OFB is a streaming mode. If the alignment between actual ciphertext and generated stream (based in IV and key) is not perfect, the original plaintext cannot be recovered.