如何构造wheel包记录文件中的散列?

2024-06-07 17:23:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要知道.whl包文件中的记录文件是如何生成的。尤其是它如何为每个文件生成sha256。。。你知道吗

例如,我们可以看到:

$ cat RECORD | grep WHEEL
pkv-X.Y.Z.dist-info/WHEEL,sha256=X8kVdBCq85ICewwfaE6btv5qKsFQfVq8NYJIXUK0i1A,104

似乎来自:

$ sha256sum <WHEEL | awk '{print $1}' | xxd -r -p | base64 | tr +/ -_ | cut -c -43
X8kVdBCq85ICewwfaE6btv5qKsFQfVq8NYJIXUK0i1A
$ wc -c <WHEEL
104

但是我想知道它是如何在python中构建的,因为我对trcut -c -43转换有点信任 注意:在其他文件上tr似乎是正确的,即/->;_+->;-,但是我希望python源代码对此负责。。。你知道吗

在python3.7中,到目前为止

python3 -c "import hashlib; import base64; print(base64.b64encode(hashlib.sha256(open('WHEEL', 'rb').read()).digest()))"
b'X8kVdBCq85ICewwfaE6btv5qKsFQfVq8NYJIXUK0i1A='

注意:到目前为止,我已经查看了https://github.com/pypa/setuptools内没有任何运气。。。你知道吗


Tags: 文件importgt记录recordtrcathashlib
0条回答
网友
1楼 · 发布于 2024-06-07 17:23:19

你应该看看https://github.com/pypa/pip/blob/c9df690f3b5bb285a855953272e6fe24f69aa08a/src/pip/_internal/wheel.py#L71-L84

def rehash(path, blocksize=1 << 20):
    # type: (str, int) -> Tuple[str, str]
    """Return (hash, length) for path using hashlib.sha256()"""
    h = hashlib.sha256()
    length = 0
    with open(path, 'rb') as f:
        for block in read_chunks(f, size=blocksize):
            length += len(block)
            h.update(block)
    digest = 'sha256=' + urlsafe_b64encode(
        h.digest()
    ).decode('latin1').rstrip('=')
    # unicode/str python2 issues
    return (digest, str(length))  # type: ignore

可以使用bash命令在manylinux2010图像中执行以下操作:

/opt/_internal/cpython-3.7.3/bin/python3 -c "\
import hashlib;\
import base64;\
print(\
 base64.urlsafe_b64encode(\
 hashlib.sha256(open('FILE_NAME', 'rb').read()).digest())\
 .decode('latin1')\
 .rstrip(b'=')\
 )"

相关问题 更多 >

    热门问题