如何使用 gpg 加密来自请求 post 的文件

How can I encrypt files from request post with gpg

是否可以根据请求 post 加密文件?怎么样?

files = request.FILES[files]
gpg = gnupg.GPG(homedir='/home/XXXX/.gnupg')
gpg.encrypt(files) <-- This do exception

异常:

'InMemoryUploadedFile' object has no attribute 'encode'

正如 the documentation you should pass a string to encrypt(), not a file. encrypt() is certainly trying to get the encoded string by trying to call .encode() 在论证中所说的那样。

您可以找到加密文件的示例 here

我找到了解决方案:

def encrypt(self, files):
    gpg = gnupg.GPG(gnupghome='/home/XXXX/.gnupg')        
    encrypted = gpg.encrypt_file(files, recipients='mail@mail.com', passphrase='secret')
    f = tempfile.NamedTemporaryFile(delete=False)
    name = f.name
    f.write(encrypted.data)
    f.close()
    return open(name, 'r+b')      

def decrypt(self, files):
    gpg = gnupg.GPG(gnupghome='/home/XXXX/.gnupg')    
    result = gpg.decrypt(files.content).data
    return result