首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用GPG加密python 3中的文件和子进程

用GPG加密python 3中的文件和子进程
EN

Stack Overflow用户
提问于 2015-07-19 12:28:02
回答 1查看 3.2K关注 0票数 3

如何使用子进程加密文件,以便输出将是字符串。

代码语言:javascript
复制
 password = '%030x' % random.randrange(16**30)
 encrypted_file = subprocess.geststatusoutput("echo "+password+
 "|gpg --password-fd 0 < "+ name_of_selected_file)

我希望加密的_file是一个字符串,这样我就可以使用它作为加密文件与post请求一起上传。

用gnupg库做这件事的最好方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-19 13:48:23

您可以使用subprocess.Popen()执行如下所示的gpg命令:

代码语言:javascript
复制
import shlex
import random
from subprocess import Popen, PIPE

passphrase = '%030x' % random.randrange(16**30)
source_filename = '/tmp/somefile'
cmd = 'gpg --batch --symmetric --cipher-algo AES256 --passphrase-fd 0 --output - {}'.format(source_filename)

# error handling omitted
p = Popen(shlex.split(cmd), stdout=PIPE, stdin=PIPE, stderr=PIPE)
encrypted_data = p.communicate(passphrase.encode())[0]

# Decryption - should work for Python 2 & 3
import os

r, w = os.pipe()    # pipe for sending passphrase from parent to child
try:
    os.set_inheritable(r, True)
except AttributeError:      # new in version 3.4
    pass
cmd = 'gpg --batch --decrypt --passphrase-fd {}'.format(r)
p = Popen(shlex.split(cmd), stdout=PIPE, stdin=PIPE, stderr=PIPE, close_fds=False)
os.close(r)    # closes fd in parent, child needs it
f = os.fdopen(w, 'w')
f.write(passphrase + '\n')    # '\n' seems required for Python 2 ???
f.close()
decrypted_data, stderr = p.communicate(encrypted_data)

# check that data was successfully roundtripped
assert open(source_filename).read() == decrypted_data.decode()

或者,只对Python 3解密:

代码语言:javascript
复制
import os
r, w = os.pipe()
cmd = 'gpg --batch --decrypt --passphrase-fd {}'.format(r)
p = Popen(shlex.split(cmd), stdout=PIPE, stdin=PIPE, stderr=PIPE, pass_fds=(r,))
os.close(r)    # closes fd in parent, child needs it
open(w, 'w').write(passphrase)
decrypted_data, stderr = p.communicate(encrypted_data)

# check that data was successfully roundtripped
assert open(source_filename).read() == decrypted_data.decode()

现在,我并不是这个方法安全性方面的专家,但是,使用communicate()直接将密码写到子进程的stdin比在命令行中回显密码更好--任何可以运行ps或类似命令的人都可以看到这个密码。

此外,依赖命令的shell级IO重定向将需要将shell=True参数转换为Popen,这可能会带来其他安全问题(请参阅Popen()文档中的警告)。

在我的gpg命令中,我假设您打算使用对称加密(您的示例并没有提出相反的建议)。如果远程服务器需要能够解密加密的文件内容,那么如何共享生成的密码呢?

你最好还是用公钥密码代替。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31501191

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档