【问题标题】:Python tar a directory and symmetric encrypt with gpgPython tar 一个目录并使用 gpg 进行对称加密
【发布时间】:2018-05-25 01:04:54
【问题描述】:

此时脚本非常适合单个文件。当给定目录时,它使用 tar 创建一个运行良好的单一文件,然后使用提供的密码对 tar 文件进行 gpg 加密。 gpg 也可以。问题是,当您解密 gpg 文件时,tar 每次都会损坏。我试图在这里找出我做错了什么。请帮忙。

#!/usr/bin/env python3
# Takes file in does symmetric encryption with the password you provide
# then  adds it to a running IPFS(ipfs.io) instance.   
#
import os
import argparse
import gnupg
import ipfsapi
import tarfile

# Parse command arguments
parser = argparse.ArgumentParser(description='Encrypt file/directory and add it to IPFS')
parser.add_argument('-i','--input', help='File.txt or Directory', required=True)
parser.add_argument('-p','--password', help='Password to encrypt with', required=True)
args = parser.parse_args()

# Set GPG Home directory
gpg = gnupg.GPG(homedir='')
# Set GPG Encoding
gpg.encoding = 'utf-8'
# Get dataToEncrypt full path
dataToEncrypt = (os.path.abspath(args.input))
# Setup tar filename to end with .zip
tarFile = ("{}.tar".format(dataToEncrypt))
# Setup encrypted filename to end with .gpg
encryptedFile = ("{}.tar.gpg".format(dataToEncrypt))
# Tell module where IPFS instance is located
api = ipfsapi.connect('127.0.0.1', 5001)

def dataTar():
    if os.path.isfile(dataToEncrypt):
        return
else:
    #return
    with tarfile.open(tarFile, 'w|') as tar:
        tar.add(dataToEncrypt)
        tar.close()

def encryptFile():
    passphrase = (args.password)
    if os.path.isfile(dataToEncrypt):
        with open(dataToEncrypt, 'rb') as f:
            status = gpg.encrypt(f,
            encrypt=False,
            symmetric='AES256',
            passphrase=passphrase,
            armor=False,
            output=dataToEncrypt + ".gpg")

    else:
        with open(tarFile, 'rb') as f:
            status = gpg.encrypt(f,
            encrypt=False,
            symmetric='AES256',
            passphrase=passphrase,
            armor=False,
            output=dataToEncrypt + ".tar.gpg")
        print ('ok: ', status.ok)
        print ('status: ', status.status)
        print ('stderr: ', status.stderr)


def ipfsFile(encryptedFile):
    # Add encrypted file to IPFS
    ipfsLoadedFile = api.add(encryptedFile, wrap_with_directory=True)
    # Return Hash of new IPFS File
    fullHash = (ipfsLoadedFile[1])
    ipfsHash = fullHash['Hash']
    return(ipfsHash)

def delEncryptedFile(encryptedFile):
    try:
        os.remove(encryptedFile)
    except:
        print("Error: %s unable to find or delete file." % encryptedFile)


def main():
    dataTar()
    encryptFile()
    #ipfsFile(encryptedFile)
    #print ("File encrypted and added to IPFS with this hash " + ipfsFile(encryptedFile))
    #delEncryptedFile(encryptedFile)

if __name__ == "__main__":
    main()

【问题讨论】:

  • 你是如何解密和解压的?
  • 我只是在做以下事情:gpg -d archive.tar.gpg |焦油xz
  • 好的。做gpg -d archive.tar.gpg | tar xvf -。不需要z。我们还需要一个尾随-。它对我有用。但是提取有点奇怪?
  • 刚刚得到这个:tar:损坏的 tar 存档 tar:重试... tar:损坏的 tar 存档 tar:重试...

标签: python tar gnupg


【解决方案1】:

代码看起来不错。我刚刚用https://pypi.org/project/python-gnupg/ 试了一下,效果很好。我必须根据这个包修复 API,但我认为这并不重要。只需比较它即可查看更改。除了您应该使用gpg -d file.tar.pgp | tar xvf - 之外,我没有看到任何问题。

#!/usr/bin/env python3
# Takes file in does symmetric encryption with the password you provide then
# adds it to a running IPFS (ipfs.io) instance.

import os
import argparse
import gnupg
import tarfile

parser = argparse.ArgumentParser(
    description='Encrypt file/directory and add it to IPFS')
parser.add_argument('-i','--input',
                    help='File.txt or Directory',
                    required=True)
parser.add_argument('-p','--password',
                    help='Password to encrypt with',
                    required=True)
args = parser.parse_args()

gpg = gnupg.GPG()
gpg.encoding = 'utf-8'
dataToEncrypt = (os.path.abspath(args.input))
tarFile = ("{}.tar".format(dataToEncrypt))
encryptedFile = ("{}.tar.gpg".format(dataToEncrypt))


def dataTar():
    if os.path.isfile(dataToEncrypt):
        return
    else:
        with tarfile.open(tarFile, 'w|') as tar:
            tar.add(dataToEncrypt)
            tar.close()

def encryptFile():
    passphrase = (args.password)
    if os.path.isfile(dataToEncrypt):
        with open(dataToEncrypt, 'rb') as f:
            status = gpg.encrypt(f.read(),
            recipients=None,
            symmetric='AES256',
            passphrase=passphrase,
            armor=False,
            output=dataToEncrypt + ".gpg")

    else:
        with open(tarFile, 'rb') as f:
            status = gpg.encrypt(f.read(),
            recipients=None,
            symmetric='AES256',
            passphrase=passphrase,
            armor=False,
            output=dataToEncrypt + ".tar.gpg")
        print ('ok: ', status.ok)
        print ('status: ', status.status)
        print ('stderr: ', status.stderr)


def ipfsFile(encryptedFile):
    ipfsLoadedFile = api.add(encryptedFile, wrap_with_directory=True)
    fullHash = (ipfsLoadedFile[1])
    ipfsHash = fullHash['Hash']
    return(ipfsHash)

def delEncryptedFile(encryptedFile):
    try:
        os.remove(encryptedFile)
    except:
        print("Error: %s unable to find or delete file." % encryptedFile)


def main():
    dataTar()
    encryptFile()

if __name__ == "__main__":
    main()

【讨论】:

  • 代码运行良好,但是当您解密 gpg 文件时,内容是否损坏?
  • 不,它对我来说很好用。 gpg -d file.tar.pgp | tar xvf - 是我使用的确切命令。
  • 好吧,如果代码好并且gpg | tar decrypt 对你有用我不知道我是如何得到错误的。 tar:损坏的 tar 存档有什么建议吗?
  • 如何加密文件? --input <dir>?
  • 是的。输入 --input ~/testing/dir.to.backup -p 密码
猜你喜欢
  • 1970-01-01
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2016-06-05
  • 1970-01-01
相关资源
最近更新 更多