如何使用子进程加密文件,以便输出将是字符串。
password = '%030x' % random.randrange(16**30)
encrypted_file = subprocess.geststatusoutput("echo "+password+
"|gpg --password-fd 0 < "+ name_of_selected_file)我希望加密的_file是一个字符串,这样我就可以使用它作为加密文件与post请求一起上传。
用gnupg库做这件事的最好方法是什么?
发布于 2015-07-19 13:48:23
您可以使用subprocess.Popen()执行如下所示的gpg命令:
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解密:
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命令中,我假设您打算使用对称加密(您的示例并没有提出相反的建议)。如果远程服务器需要能够解密加密的文件内容,那么如何共享生成的密码呢?
你最好还是用公钥密码代替。
https://stackoverflow.com/questions/31501191
复制相似问题