【问题标题】:Decrypting zip file encrypted by gpg解密由gpg加密的zip文件
【发布时间】:2018-11-10 15:05:30
【问题描述】:

当我尝试使用下面的 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()

【问题讨论】:

  • 您“无法获得”是什么意思? gpg.decrypt() 是否返回任何内容?如果是这样,我怀疑这将是解密的文件。

标签: python encryption gnupg


【解决方案1】:

见docs for gnupg:

要解密消息,请使用以下方法:
>>> decrypted_data = gpg.decrypt(data)

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

但是,您还有另一个问题。 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)

【讨论】:

    【解决方案2】:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 1970-01-01
      • 2021-07-12
      • 2019-08-10
      • 2018-02-23
      • 2018-12-27
      • 1970-01-01
      相关资源
      最近更新 更多