【问题标题】:How do I secure my pickle files correctly?如何正确保护我的泡菜文件?
【发布时间】:2021-03-03 08:16:26
【问题描述】:

我正在关注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', data, 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', 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

【问题讨论】:

    标签: python python-3.x encoding pickle hmac


    【解决方案1】:

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

    参考资料:

    【讨论】:

    • 这几乎对我有用。由于某些奇怪的原因,我不得不导入编解码器文件并以这种方式进行转换,而不仅仅是使用.encode()。这对我来说没有意义
    【解决方案2】:

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

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

    不知道为什么使用.encode().decode() 仍然不适合我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 2017-03-22
      • 1970-01-01
      • 2023-01-04
      相关资源
      最近更新 更多