2017-03-06 36 views
-1

我寫了兩個python腳本。其中一個將文件編碼爲二進制文件,將其作爲文本文件存儲以供以後解密。另一個腳本可以將文本文件恢復爲可讀信息,至少,這是我的目標。Python的二進制文件了一些文件

腳本1(加密) (使用任何的PNG圖片文件作爲輸入,任何.txt文件作爲輸出):

u_input = input("What file to encrypt?") 
file_store = input("Where do you want to store the binary?") 
character = "" #Blank for now 
encrypted = "" #Blank for now, stores the bytes before they are written 

with open(u_input, 'rb') as f: 
    while True: 
     c = f.read(1) 
     if not c: 
      f.close() 
      break 
     encrypted = encrypted + str(bin(ord(c))[2:].zfill(8)) 
print("") 
print(encrypted) # This line is not necessary, but I have included it to show that the encryption works 
print("") 
with open(file_store, 'wb') as f: 
    f.write(bytes(encrypted, 'UTF-8')) 
    f.close() 

據我所知,這工作好文本文件(。 TXT)

我再有第二個腳本(解密文件) 使用之前創建的.txt文件的來源,任何.png文件作爲目的地:

u_input =("Sourcefile:") 
file_store = input("Decrypted output:") 
character = "" 
decoded_string = "" 

with open(u_input, 'r' as f: 
    while True: 
     c = f.read(1) 
     if not c: 
      f.close() 
      break 
     character = character + c 
     if len(character) % 8 == 0: 
      decoded_string = decoded_string + chr(int(character, 2)) 
      character = "" 

with open(file_store, 'wb') as f: 
    f.write(bytes(decoded_string, 'UTF-8')) 
    f.close() 
    print("SUCCESS!") 

部分工作。即它寫入文件。但是,我無法打開或編輯它。當我比較我的原始文件(img.png)與我的第二個文件(img2.png)時,我看到字符已被替換或換行符輸入不正確。我無法在任何圖像查看/編輯程序中查看該文件。我不懂爲什麼。

請有人嘗試解釋並提供解決方案(雖然,部分)?提前致謝。

注:我知道我使用「加密」和「解密」不一定正確使用,但這是一個個人項目,所以它並不重要,我

+0

'「%s」%u_input'?你期望做什麼'u_input'不能自行完成? –

+0

感謝您的建議,相應地編輯了我的腳本 –

+0

您想實現什麼目標?它看起來像你在滾動你自己的編解碼器,但你可能只需要使用base64。 –

回答

0

看樣子你使用Python 3,因爲您在bytes調用中輸入了UTF-8參數。這是你的問題 - 輸入應該被解碼爲一個字節字符串,但是你將一個Unicode字符串放在一起,而轉換不是1:1。這很容易修復。

decoded_string = b"" 
# ... 
decoded_string = decoded_string + bytes([int(character, 2)]) 
# ... 
f.write(decoded_string) 

對於既適用於Python 2又適用於Python 3的版本,另一個小修改。在Python 3.5中,這實際上對我來說測量速度更快,所以它應該是首選的方法。

import struct 
# ... 
decoded_string = decoded_string + struct.pack('B', int(character, 2)) 
+0

我馬上試試這個,我會讓你知道結果。 –

+0

感謝您的幫助,這已修復了我的程序,現在它應該可以正常工作。非常感激。 –

+0

請幫忙,我試着在不同的python安裝上運行代碼,現在輸出的文件中包含方括號,裏面有數字而不是數據。我能做些什麼來解決這個問題?謝謝。 –