2014-10-07 98 views
-2

我試圖使用對稱密鑰來加密文件。因爲我無法O此,我做使用文件(.txt)內容和加密相同的內容使用對稱密鑰一些測試,一切正常:使用對稱密鑰的文件加密

filename1 = raw_input("Insert file name: ") 
with open(filename1,'rb') as f: 
    s = f.read() 

data1 = s 


# insert password to create key 

password1 = raw_input('Enter password (symmetric key): ') 

# generate 16bytes (AES-128) key from inserted password 
h1 = SHA256.new() 
h1.update(password1) 
key1 = h1.digest()[0:16] 

# generate initialization 16bytes vector 
iv1 = Random.new().read(16) 

# criptogram creation (cipher data) 
cipher1 = AES.new(key1, AES.MODE_CFB, iv1) 
criptogram1 = iv1 + cipher1.encrypt(data1) 

但是,我需要的是使用對稱密鑰對加密文件進行加密,而不僅僅是像我目前所做的那樣的內容。我需要能夠選擇文件,然後在其中使用對稱密鑰。

編輯:「密碼文件,而不僅僅是內容」?我的意思是我可以加密一個.txt文件裏面的東西,裏面寫了一些東西,但是我希望能夠直接加密這個文件,我不想打開它並閱讀裏面的內容然後加密。 .. 我發佈的例子中,我輸入了一個文件名(例如xpto.txt),裏面寫了一些東西(例如Hello world!),所以在這個例子中我只是加密了這個內容。

我想得到一個加密出來的文件必須讀取裏面的內容。因爲如果我嘗試對圖片進行加密,我不會像在.txt文件中那樣讀取它,我想要獲取整個文件並對其進行加密。

+3

你是什麼意思的「密碼文件,而不僅僅是內容」嗎?當然,加密文件意味着加密其內容..:confused: – redShadow 2014-10-07 10:47:22

+1

這不是很明顯,你想要什麼,你有什麼,以及你期望如何達到你的目標。請**舉例輸入和輸出**需要和*解釋*你一直在試圖做到這一點。 – Veedrac 2014-10-07 10:57:15

+0

你的問題沒有多大意義。您不會像文本文件那樣讀取圖片文件,您可以用二進制模式打開它,並讀取/加密其中的數據塊。您可以用完全相同的方式處理文本文件。檢查'open(...)'函數的文檔,你會想要通過「rb」模式將其設置爲二進制模式。 – 2014-10-07 12:42:44

回答

0

如果我說得對 - 您可以加密當前文件中的某些內容,但是您不知道如何從「myfile1.py」運行腳本,該腳本將加密「myfile2.txt」中的行, ?

也只是讀第二個文件中的第一個文件線,像命令:

with open('myfile2.txt') as myfile: 
    mytext = myfile.readlines() 

,然後做加密的mytext

0

經過一番研究,我設法找到一個解決方案:

#read binary file to get bytes 
    while True: 
     buf = fo.read(1024) #read 1024bytes from the file on each iteration of the loop 
     if len(buf) == 0: 
      break 

    fo.close() 


    # insert password to create key 

    password1 = raw_input('Enter password (symmetric key): ') 

    # generate 16bytes (AES-128) key from inserted password 
    h1 = SHA256.new() 
    h1.update(password1) 
    key1 = h1.digest()[0:16] 

    # generate initialization 16bytes vector 
    iv1 = Random.new().read(16) 

    # criptogram creation (cipher data) 
    cipher1 = AES.new(key1, AES.MODE_CFB, iv1) 
    criptogram1 = iv1 + cipher1.encrypt(buf)