解密由gpg加密的zip文件

Decrypting zip file encrypted by gpg

当我尝试使用下面的 cmd 在 shell 中解密此文件时:

gpg test.zip.asc

通过后,我在同一文件夹中获得解密文件 "test.zip",但使用 python 脚本我无法获得解密文件。没有发生错误,知道我做错了什么吗?

import gnupg

def testgpg():    
    print "testgpg function started"

    encrypted_file = "test.zip.asc"
    passwd = "passwd"
    gpg = gnupg.GPG(gnupghome='/home/centos/.gnupg')
    try:
        print "trying"
        gpg.decrypt(encrypted_file, passphrase=passwd)
        print "decrypted"
    except Exception as e:
        print "not decrypted: -->", str(e)

testgpg()

参见 docs for gnupg:

To decrypt a message, use the following approach:
>>> decrypted_data = gpg.decrypt(data)

该模块不会像 gpg 二进制文件一样解密文件并将其保存在与原始文件相同的目录中。相反,它 returns 一串解密数据。

但是,您还有另一个问题。 gpg.decrypt() 试图解密存储在 encrpyted_file 中的值,这当然只是字符串 "test.zip.asc"。相反,您想解密具有该名称的文件的内容。为此,您需要像这样使用 gpg.decrypt_file()

# Open the encrypted file (gpg will handle reading it)
with open(encrypted_file, 'rb') as src:
    # decrypt the file and store its decrypted contents
    decrypted_contents = gpg.decrypt_file(src, passphrase=passwd)
    # write the decrypted contents to a new file
    with open('destination_file.zip', 'wb') as dst:
        dst.write(decrypted_contents)

decrypt_file 方法允许提供输出文件的路径,如下所示:

gpg = gnupg.GPG(gnupghome=config.gnupgHome)
with open(encryptedZippedApp, 'rb') as src:
    status = gpg.decrypt_file(src, output='/tmp/myout.zip')

print('ok: ', status.ok)