1

python和编程新手。目前正在编写一些 python 3 代码来保存我的银行帐户登录详细信息等。我已经通过打开和关闭文件并使用 gnupg 模块的 out='filename' 让它工作,但理想情况下我希望它写入记忆,因为如果可以避免的话,我不希望磁盘上的解密信息。

该文件由程序中的另一个函数创建,该函数腌制字典并将其加密为文件。但是,当我尝试用这个解密并打开它时:

def OpenDictionary():
    """ open the dictionary file """
    if os.path.isfile(SAVEFILE):
        f = open(SAVEFILE, 'rb')
        print('opening gpg file')
        buf = io.BytesIO()
        decrypted_data = gpg.decrypt_file(f, passphrase=PASSWORD)
        buf.write(decrypted_data.data)
        print ('ok: ', decrypted_data.ok)
        print ('status: ', decrypted_data.status)
        print ('stderr: ', decrypted_data.stderr)
        f.close()
        dictionary = pickle.load(buf)
        buf.close()
        return dictionary

我得到:

Traceback (most recent call last):   File "C:\Users\Josh Harney\Dropbox\Python-pys\gpg-banks.py", line 179, in <module>
    main(sys.argv[1:])   File "C:\Users\Josh Harney\Dropbox\Python-pys\gpg-banks.py", line 173, in main
    dictionary = OpenDictionary()   File "C:\Users\Josh Harney\Dropbox\Python-pys\gpg-banks.py", line 87, in OpenDictionary
    dictionary = pickle.load(buf) EOFError

我的 Linux 机器上的结果相同。我已经尝试了很多东西来完成这项工作,到目前为止还没有运气。谁能建议一个更好的方法来做到这一点?基本上我需要让 gpg.decrypt_file 输出到缓冲区或变量,然后 pickle.load 将其读回字典。

4

1 回答 1

0
def OpenDictionary():
""" open the dictionary file """
try:
    if os.path.isfile(SAVEFILE):
        f = open(SAVEFILE, 'r')
        enc_data = f.read()
        print('opening gpg file')
        decrypted_data = gpg.decrypt(enc_data, passphrase=PASSWORD)
        print ('ok: ', decrypted_data.ok)
        print ('status: ', decrypted_data.status)
        print ('stderr: ', decrypted_data.stderr)
        f.close()
        dictionary = pickle.loads(decrypted_data.data)
        return dictionary
except Exception as e:
    print('Something Snaggy happened in the call OpenDictionary(), it looks like: ', e)


def SaveDictionary(dictionary):
    savestr = pickle.dumps(dictionary)
    status = gpg.encrypt(savestr, recipients=['my@email'])
    if status.ok == True:
        print('scrap buffer')
        f = open(SAVEFILE, 'w')
        f.write(str(status))
        f.close()
    else:
        print('Something went wrong with the save!!!')

    print ('ok: ', status.ok)
    print ('status: ', status.status)
    print ('stderr: ', status.stderr)

感谢@senderle

于 2012-12-09T16:51:38.100 回答