简体   繁体   English

如何正确保护我的泡菜文件?

[英]How do I secure my pickle files correctly?

I'm following this guide to secure the pickle files correctly but I'm not getting the same output.我正在按照本指南正确保护泡菜文件,但我没有得到相同的 output。 Granted I had to do some changes to run it the first time:当然,我必须做一些更改才能第一次运行它:

import hashlib
import hmac
import pickle


class Dummy:
    pass


obj = Dummy()
data = pickle.dumps(obj)
digest = hmac.new(b'unique-key-here', data, hashlib.blake2b).hexdigest()
with open('temp.txt', 'wb') as output:
    output.write(str(digest) + ' ' + data)

with open('temp.txt', 'r') as f:
    data = f.read()

digest, data = data.split(' ')
expected_digest = hmac.new(b'unique-key-here', data, hashlib.blake2b).hexdigest()

if not secrets.compare_digest(digest, expected_digest):
    print('Invalid signature')
    exit(1)

obj = pickle.loads(data)

When I run this I get the following stacktrace:当我运行它时,我得到以下堆栈跟踪:

  File "test.py", line 21, in <module>
    expected_digest = hmac.new(b'unique-key-here', data, hashlib.blake2b).hexdigest()
  File "/usr/lib/python3.8/hmac.py", line 153, in new
    return HMAC(key, msg, digestmod)
  File "/usr/lib/python3.8/hmac.py", line 88, in __init__
    self.update(msg)
  File "/usr/lib/python3.8/hmac.py", line 96, in update
    self.inner.update(msg)
TypeError: Unicode-objects must be encoded before hashing

Your problem is data = f.read() .你的问题是data = f.read() .read() returns a string and hmac.new() wants bytes . .read()返回一个字符串,而hmac.new() bytes Change the problem line to data = f.read().encode('utf-8') OR read the file in binary mode ( 'b' flag).将问题行更改为data = f.read().encode('utf-8')或以二进制模式读取文件( 'b'标志)。

References:参考:

I ended up having to use the following methods for it to work:我最终不得不使用以下方法使其工作:

pickle.loads(codecs.decode(pickle_data.encode(), 'base64'))
# and
codecs.encode(pickle.dumps(pickle_obj), "base64").decode()

Not sure why using .encode() and .decode() was still not working for me.不知道为什么使用.encode().decode()仍然不适合我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM