aboutcode-org / aboutcode-org/scancode-toolkit

Hash is unexpectedly None for empty files

未关闭
#4,428 11 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看
documentation
主要语言
Python
星标
2.6k
派生
791
平均合并
1 天 12 小时
30 天内合并 PR
5

描述

Generating hashes for empty files will always return `None`, which is not documented and different from the usual hashing algorithms as well as contradicting the SPDX standard.

Example:

```python3
from commoncode.hash import sha1
from hashlib import sha1 as sha1_hashlib
from tempfile import NamedTemporaryFile

with NamedTemporaryFile() as temporary_file:
temporary_file.write(b'')
temporary_file.seek(0)
print(sha1(location=temporary_file.name))
print(sha1_hashlib(string=temporary_file.read(), used_for_security=False).hexdigest())
```

The reason seems to be that https://github.com/aboutcode-org/commoncode/blob/878be6140deac30e2b95fb0fad9eb8feca015fc8/src/commoncode/hash.py#L38 does not use `msg is not None`, but basically `bool(msg)`, which is `False` for empty inputs as well.

Replacing the line with

```python3
self.h = msg is not None and hmodule(msg).digest()[:self.digest_size] or None
```

(as well as replacing the same pattern in `sha1_git_hasher`) seems to fix this issue.

贡献指南

打开贡献指南

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。