为什么我没有把sha256做好

Why am I not getting the sha256 right?

本文关键字:sha256 做好 为什么      更新时间:2023-10-16

我正在使用crypto++库进行一些练习。我期望得到与从shell调用的sha256sum工具相同的输出。

// typedef unsigned char byte;
byte out[CryptoPP::SHA256::DIGESTSIZE];
byte in=65;  // 'A'
CryptoPP::SHA256().CalculateDigest(out, &in, 1);
for(int i=0; i < CryptoPP::SHA256::DIGESTSIZE; i++)
    std::cout << std::hex << (int)out[i];
std::cout << std::endl;

559aead08264d5795d399718cdd5bd49572e84fe55590eef31a88a08fdffd

$ echo A | sha256sum

06f961b802bc46ee168555f066d28f4f0e9afdf3f88174c1ee6f9de004fc30a0

为什么两者不相等?

echo会添加一行换行符,因此您可以比较不同字符串的哈希值。改为使用printf

$ printf 'A' | sha256sum
559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd  -
$ printf 'An' | sha256sum
06f961b802bc46ee168555f066d28f4f0e9afdf3f88174c1ee6f9de004fc30a0  - 

在命令行中,您正在对A+换行进行校验和。

如果您的unix版本支持它,请使用echo -n进行回显,而不添加换行符;

$ echo -n A | sha256sum
559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd  -