2016-08-21 44 views
-1

的Python 3.5,pycrypto 2.7a1,Windows中,RC2加密如何解密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文件,以便爲什麼我尋求幫助。

+0

我只能在這裏看到加密代碼。請顯示[最小,完整和可驗證示例](/ help/mcve),包括您遇到的錯誤。請注意,您需要在解密期間使用密鑰和IV的*完全相同的字節。 –

+0

@ArtjomB。編輯 – Tukanoid

回答

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

+0

非常感謝,你是最棒的!) – Tukanoid