微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何正确保护泡菜文件?

如何解决如何正确保护泡菜文件?

我正在关注此 guide 以正确保护泡菜文件,但我没有得到相同的输出。当然,我必须做一些更改才能第一次运行它:

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',hashlib.blake2b).hexdigest()

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

obj = pickle.loads(data)

当我运行它时,我得到以下堆栈跟踪:

  File "test.py",line 21,in <module>
    expected_digest = hmac.new(b'unique-key-here',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

解决方法

您的问题是data = f.read().read() 返回一个字符串,hmac.new() 需要 bytes。将问题行更改为 data = f.read().encode('utf-8') 或以二进制模式读取文件('b' 标志)。

参考文献:

,

我最终不得不使用以下方法使其工作:

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

不知道为什么使用 .encode().decode() 仍然对我不起作用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。