2016-10-04 85 views
1

在python中,使用gnupg包,是否可以在内存中取值,然后将其写入加密文件而不是写入文件THEN加密?用Python直接写入加密文件

我希望像这样的工作:

import gnupg 

gpg = gnupg.GPG(gnupghome='keydirectory') 

l = [['a', '1'], ['b', '2'], ['c', '3']] 

gpg.encrypt_file(l, recipients=['[email protected]'], output='encryptedfile.asc') 

我希望有这样一个概念写入遍历行由行,但我不能找到一个。

with open('regularfile.txt', 'w') as file: 
    for i in l: 
    file.write(i) 

理想情况下,我可以连接到数据库并通过直接写入输出文件。

回答

0

只需使用gpg.encrypt()函数而不是encrypt_file()然后写入文件。

0

documentation for the GPG.encrypt method表明,这是你想要的。

>>> import gnupg 

>>> gpg = gnupg.GPG(homedir="doctests") 
>>> key_settings = gpg.gen_key_input(
...   key_type='RSA', 
...   key_length=1024, 
...   key_usage='ESCA', 
...   passphrase='foo') 
>>> key = gpg.gen_key(key_settings) 

>>> message = "The crow flies at midnight." 
>>> encrypted = str(gpg.encrypt(message, key.printprint)) 
>>> assert encrypted != message 
>>> assert not encrypted.isspace() 

>>> decrypted = str(gpg.decrypt(encrypted)) 
>>> assert not decrypted.isspace() 
>>> decrypted 
'The crow flies at midnight.'