【发布时间】:2020-12-09 20:11:21
【问题描述】:
我是一名新开发人员。 我正在将 C# 库转换为 Python(3.8)。我有哈希函数得到 一个文件并找到它的哈希码。
在原始 C# 代码中,哈希函数返回 byte[32] 数组 但在 Python 中,我得到了十六进制代码。我也在尝试找出如何在 byte[32] 中返回代码。
这是我的python代码:
sha256_hash = hashlib.sha256()
with open(logPath, "rb") as f:
# Read and update hash string value in blocks of 4K
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
hash_code = sha256_hash.hexdigest()
这是c#代码:
using (var fileStream = fileInfo.Open(FileMode.Open))
{
fileStream.Position = position;
var sha256 = SHA256.Create();
hashValue = sha256.ComputeHash(fileStream);
fileStream.Close();
}
【问题讨论】:
-
sha256_hash.digest() -
谢谢,但后来我得到了这样的东西:b',\xb3\xc1Mn"\xbf\xb6\x98\xb6\x97\xf2j\xa9u\x08u@\xea\xb3\x1f\x17 \xc3"x\xd4_\xbb\x02Z(\xd5'
-
这是一个字节字符串,它是 .NET 字节数组的 Python 等价物。注意引号前面的
b。 -
哦,我不知道,非常感谢!如果我想将另一个字符串连接到这个字节字符串怎么办: arr = bytes("something", 'utf-8') 。我可以这样做吗? ?它们看起来不同(一个字节[7],第一个是 .NET 字节数组)
-
@MaayanPaz-Chen,
first_byte_string + second_byte_string可以解决问题。我强烈建议你花 15 分钟阅读官方 python 文档中的article about built-in types。