我正在使用https://github.com/eblocha/django-encrypted-files加密上传到服务器的文件,通过Django中的一个简单的联系人表单应用程序。django-encrypted-files在CTR模式下使用AES通过上传处理程序加密上传的文件,同时将文件流到服务器。
我要做的是通过FTP下载加密文件并在Python中本地解密,手动解密加密的文件。我不想或不需要流解密服务器上的文件或修改django-encrypted-files;我只想手动下载,然后在Python中本地解密文件。
问题是我无法让本地Python解密工作。密码学上的文档显示了一个使用Python中输入的示例文本进行加密和解密的示例。但是没有加密/解密文件的例子。
下面的代码是我试图在Python中使用的代码。通过Django上传的原始文件是uploaded_file.txt。从服务器下载的加密文件为encrypted.txt;保存解密文本的文件为decrypted.txt。
但是当我尝试下面的代码时,decrypted.txt是空的。这是写入文件的问题吗?或与iv有关的问题
在本地Python中解密AES-CTR模式文件的工作示例是什么?
uploaded_file.txt:https://paste.c-net.org/MiltonElliot
encrypted.txt:https://paste.c-net.org/ChasesPrints
Python外壳:
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
key = b'\x1a>\xf8\xcd\xe2\x8e_~V\x14\x98\xc2\x1f\xf9\xea\xf8\xd7c\xb3`!d\xd4\xe3+\xf7Q\x83\xb5~\x8f\xdd'
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(key), modes.CTR(iv))
decryptor = cipher.decryptor()
openfile = open("encrypted.txt", 'rb')
savefile = open("decrypted.txt", "wb")
read = openfile.read()
savefile.write(read[16:])
445 // output
exit但是decrypted.txt文件是空的。
这可能与此相关,也可能与此无关;这是在流到服务器时加密的功能:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from django.core.files.uploadhandler import FileUploadHandler
class EncryptedFileUploadHandler(FileUploadHandler):
"""Encrypt data as it is uploaded"""
def __init__(self, request=None, key=None):
super().__init__(request=request)
self.key = key or settings.AES_KEY
def new_file(self, *args, **kwargs):
self.nonce = os.urandom(16)
self.encryptor = Cipher(algorithms.AES(self.key),modes.CTR(self.nonce)).encryptor()
self.nonce_passed = False
return super().new_file(*args,**kwargs)
def receive_data_chunk(self, raw_data, start):
if not self.nonce_passed:
self.nonce_passed = True
return self.nonce + self.encryptor.update(raw_data)
else:
return self.encryptor.update(raw_data)
def file_complete(self, file_size):
return发布于 2022-03-22 20:10:04
在加密过程中,IV和密文连接在一起:IV || ciphertext。在解密过程中,使用了随机IV,这是错误的。相反,必须应用加密的IV。为此,必须将IV和密文分开。
此外,必须调用update()和finalize()方法,它们执行实际的解密。
以下代码实际上与您的代码相匹配,由缺少的部分进行扩展:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
# Read ciphertext
openfile = open("encrypted.txt", 'rb')
read = openfile.read()
openfile.close()
# Separate IV and ciphertext; decrypt
iv = read[:16]
ciphertext = read[16:]
key = b'\x1a>\xf8\xcd\xe2\x8e_~V\x14\x98\xc2\x1f\xf9\xea\xf8\xd7c\xb3`!d\xd4\xe3+\xf7Q\x83\xb5~\x8f\xdd'
cipher = Cipher(algorithms.AES(key), modes.CTR(iv))
decryptor = cipher.decryptor()
decrypted = decryptor.update(ciphertext) + decryptor.finalize()
# Store decrypted data
savefile = open("decrypted.txt", "wb")
savefile.write(decrypted)
savefile.close()此代码成功地解密了链接文件中的密文(使用已发布的密钥)。
https://stackoverflow.com/questions/71430014
复制相似问题