How to decrypt a RC2 ciphertext?

1.6k Views Asked by At

Python 3.5, pycrypto 2.7a1, Windows, RC2 ciphering

Example:

print('Введите текс, который хотите зашифровать:')
text = input()

with open('plaintext.txt', 'w') as f:
    f.write(text)

key = os.urandom(32)

with open('rc2key.bin', 'wb') as keyfile:
    keyfile.write(key)

iv = Random.new().read(ARC2.block_size)

cipher = ARC2.new(key, ARC2.MODE_CFB, iv)
ciphertext = iv + cipher.encrypt(bytes(text, "utf-8"))

with open('iv.bin', 'wb') as f:
    f.write(iv)

with open('ciphertext.bin', 'wb') as f:
    f.write(ciphertext)

print(ciphertext.decode("cp1251"))

And I'd like to know how can I decrypt this text, I tried, but couldn't do it.

My try to decrypt:

os.system('cls')
print('Дешифруем значит')

with open('ciphertext.bin', 'rb') as f:
    ciphertext = f.read()

with open('rc2key.bin', 'rb') as f:
    key = f.read()

with open('iv.bin', 'rb') as f:
    iv = f.read()

ciphertext = ciphertext.decode('cp1251')
iv = iv.decode('cp1251')

text =  ciphertext.replace(iv, '')
text = cipher.decrypt(text)

with open('plaintext.txt', 'w') as f:
    f.write(text)

print(text.decode("ascii"))

But I understood that I need cipher variable, and I can't save it to .txt or .bin file, so that why I'm asking for help.

1

There are 1 best solutions below

0
On BEST ANSWER

The IV is a non-secret value and is commonly written in front of the ciphertext. Since, you've done that already, you don't need to write an additional IV file. RC2 has a block size of 64 bit, so the IV will always be 8 byte long.

with open('ciphertext.bin', 'rb') as f:
    ciphertext = f.read()

with open('rc2key.bin', 'rb') as f:
    key = f.read()

iv = ciphertext[:ARC2.block_size]
ciphertext = ciphertext[ARC2.block_size:]

cipher = ARC2.new(key, ARC2.MODE_CFB, iv)
text = cipher.decrypt(ciphertext).decode("utf-8")

with open('plaintext.txt', 'w') as f:
    f.write(text)

print(text)

Other problems:

  • Don't simply decode binary data such as ciphertexts, keys or IV, because those are most likely not printable.

  • Don't re-use the same cipher object if you're doing something different. The decryption needs a freshly initialized ARC2 object.