如何解密RC2密文?

时间:2016-08-21 16:09:47

标签: python python-3.x encryption pycrypto rc2-cipher

Python 3.5,pycrypto 2.7a1,Windows,RC2加密

示例:

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"))

我想知道我怎么能解密这个文本,我试过,但是不能这样做。

我尝试解密:

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"))

但我明白我需要密码变量,而且我无法将其保存到.txt或.bin文件中,所以我要求帮助。

1 个答案:

答案 0 :(得分:0)

IV是非秘密值,通常写在密文之前。既然,您已经完成了这项工作,那么您不需要编写额外的IV文件。 RC2的块大小为64位,因此IV始终为8字节长。

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)

其他问题:

  • 不要简单地解码二进制数据,如密文,密钥或IV,因为这些数据很可能无法打印。

  • 如果您正在做不同的事情,请不要重复使用相同的cipher对象。解密需要一个刚刚初始化的ARC2对象。