【问题标题】:Invalid CRC32 Hash Generation无效的 CRC32 哈希生成
【发布时间】:2014-10-23 13:44:47
【问题描述】:

我正在使用 Crypto++ 库从纯文本创建 SHA1CRC32 哈希,如下所示:

#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <cryptopp/sha.h>
#include <cryptopp/crc.h>

#include <string.h>
#include <iostream>

int main()
{
    // Calculate SHA1

    std::string data = "Hello World";
    std::string base_encoded_string;

    byte sha_hash[CryptoPP::SHA::DIGESTSIZE];
    CryptoPP::SHA().CalculateDigest(sha_hash, (byte*)data.data(), data.size());
    CryptoPP::StringSource ss1( std::string(sha_hash, sha_hash+CryptoPP::SHA::DIGESTSIZE), true,
        new CryptoPP::HexEncoder( new CryptoPP::StringSink( base_encoded_string ) ));

    std::cout << base_encoded_string << std::endl;
    base_encoded_string.clear();

    // Calculate CRC32

    byte crc32_hash[CryptoPP::CRC32::DIGESTSIZE];
    CryptoPP::CRC32().CalculateDigest(crc32_hash, (byte*)data.data(), data.size());
    CryptoPP::StringSource ss2( std::string(crc32_hash, crc32_hash+CryptoPP::CRC32::DIGESTSIZE), true,
        new CryptoPP::HexEncoder( new CryptoPP::StringSink( base_encoded_string ) ));

    std::cout << base_encoded_string << std::endl;
    base_encoded_string.clear();

}

我得到的输出是:

0A4D55A8D778E5022FAB701977C5D840BBC486D0
56B1174A
按任意键继续 。 . .

并且,其中我根据各种在线资源确认CRC32不正确,例如:http://www.fileformat.info/tool/hash.htm?text=Hello+World

我不知道为什么,因为我正在按照与 SHA1 相同的过程创建 CRC32 哈希。真的有不同的方式还是我真的在这里做错了什么?

【问题讨论】:

    标签: hash sha1 crypto++ crc32


    【解决方案1】:

    字节 crc32_hash[CryptoPP::CRC32::DIGESTSIZE];

    我相信你有一个糟糕的字节序交互。将 CRC32 值视为整数,而不是字节数组。

    所以试试这个:

    int32_t crc = (crc32_hash[0] << 0) | (crc32_hash[1] << 8) |
                    (crc32_hash[2] << 16) | (crc32_hash[3] << 24);
    

    如果 crc32_hash 是整数对齐的,那么你可以:

    int32_t crc = ntohl(*(int32_t*)crc32_hash);
    

    或者,这可能更容易:

    int32_t crc32_hash;
    CryptoPP::CRC32().CalculateDigest(&crc32_hash, (byte*)data.data(), data.size());
    

    我对@9​​87654325@ 可能有误,可能是uint32_t(我没有看标准)。

    【讨论】:

      猜你喜欢
      • 2015-12-06
      • 2021-08-22
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-26
      • 2016-10-31
      • 1970-01-01
      相关资源
      最近更新 更多