2
我正在實現一個Django網站,其中上傳的文件使用用戶提供的密鑰進行加密,然後將其保存在服務器(/ media)上。當用戶希望查看它們時,會提示他們輸入密鑰,解密加密文件,然後顯示它們。這裏是我的加密/解密文件代碼:Django加密密鑰完整性
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
def encryption_pad(string):
pad = b"\0" * (AES.block_size - len(string) % AES.block_size)
padded_string = string + pad
return padded_string
def encrypt_file(key, file):
with open(file, 'rb') as out:
byte_output = out.read()
hash = SHA256.new()
hash.update(key)
byte_output = encryption_pad(byte_output)
initialization_vector = Random.new().read(AES.block_size)
cipher = AES.new(hash.digest(), AES.MODE_CBC, initialization_vector)
encrypted_output = initialization_vector + cipher.encrypt(byte_output)
with open(file + ".enc", 'wb') as out:
out.write(encrypted_output)
def decrypt_file(file, key):
with open(file, 'rb') as input:
ciphertext = input.read()
hash = SHA256.new()
hash.update(key)
initialization_vector = ciphertext[:AES.block_size]
cipher = AES.new(hash.digest(), AES.MODE_CBC, initialization_vector)
decrypted_output = cipher.decrypt(ciphertext[AES.block_size:])
decrypted_output = decrypted_output.rstrip(b"\0")
with open(file[:-4], 'wb') as output:
output.write(decrypted_output)
我是比較新的安全,所以我的問題是:對於此設置必須在服務器的內存中存在的時間有些長的鑰匙,那麼什麼是正確的方法我的views.py函數將它們傳遞給這個模塊,然後妥善處理它們?
感謝您的解釋和參考,大的幫助 – Kdawg 2014-12-02 22:00:23