2014-08-29 115 views
0

我创建SHA1,并使用加密+图书馆下面从纯文本CRC32哈希:无效CRC32哈希生成

#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

我不知道为什么,因为我按照相同的程序,创建CRC32哈希我遵循SHA1。有没有真正不同的方法,或者我在这里真的做错了什么?

回答

1

byte crc32_hash [CryptoPP :: CRC32 :: DIGESTSIZE];

我相信你有一个糟糕的endian互动。对待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()); 

我可能对于int32_t可能是错误的,可能是uint32_t(我没看标准)。