python - 有没有办法安全地存储 SHA256 哈希的内部状态

标签 python hashlib

我正在寻找一种方法来在 python 中存储 sha256 哈希的内部状态,然后稍后将其取回,以便我可以继续对代码之前中断的内容流进行哈希处理。

我想这可以通过 pickle 实现,但这会带来安全风险,因为我想在外部存储状态。

有什么方法可以获取 hashlib.sha256() 的内部位/字节,然后根据这些相同的内部字节创建一个新的位/字节。 IE:这就好像后来创建的那个是通过第一个上的 copy() 方法创建的一样。

更多上下文

我正在将数据 block 上传到 AWS S3,最终将形成分段上传。它们按严格的顺序发送,最初将以自己的权利作为 S3 对象上传。全部上传后,将使用 upload_part_copy 将它们合并到一个对象中.在流程结束时,我想知道组合对象的最终 SHA256 哈希值。

在上传所有部分之前,我不会知道完整的文件内容,因此无法提前知道 SHA256 哈希。需要使此过程可恢复。我不想做的是下载 500GB 的内容只是为了重新计算哈希值。

我的想法是,我可以在上传时维护一个 hashlib.sha256() 对象,然后我可以在每次上传一大块时提取哈希对象的内部状态数据并将其作为元数据附加到 block 中。如果我需要恢复,那么我需要做的就是获取最后一个 block 上的元数据并恢复哈希对象。

最佳答案

Rehash:可恢复哈希库

https://github.com/kislyuk/rehash

Rehash is a resumable interface to the OpenSSL-based hashers (message digest objects) in the CPython hashlib standard library. Rehash provides hashers that can be pickled, persisted and reconstituted from their repr(), and otherwise serialized. The rest of the Rehash API is identical to hashlib.

Rehash hashers can be used to checkpoint and restore progress when hashing large byte streams:

import pickle, rehash
hasher = rehash.sha256(b"foo")
state = pickle.dumps(hasher)

hasher2 = pickle.loads(state)
hasher2.update(b"bar")

assert hasher2.hexdigest() == rehash.sha256(b"foobar").hexdigest()

__getstate____setstate__

import rehash
hasher = rehash.sha256(b"foo")
state = hasher.__getstate__()

hasher2 = rehash.sha256()
hasher2.__setstate__(state)
hasher2.update(b"bar")

关于python - 有没有办法安全地存储 SHA256 哈希的内部状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73583918/

相关文章:

python - hashlib - 为什么摘要匹配但裸对象不匹配?

python - Python 中的 MD5 哈希函数更改数据

Python:使用 Pyparser 测试数据的语法无效

python - 如何确定 Python 中 utf-8 编码字符串的字节长度?

Python key 错误 : pandas: match row value to column name/key where some keys are missing

python - 确定目录中是否添加、删除或修改了任何文件

python - Pandas 查询无值

python - 如何在discord.py中捕获错误并发送响应?

python - 对 Python 哈希的操作

Python 数据/文件 Crc