Generating a SHA256 hash with Crypto++, using a string as input and output?

后端 未结 3 2083
孤独总比滥情好
孤独总比滥情好 2021-01-31 10:43

I need an example of how to use Crypto++ to generate a SHA256 hash from a std::string and output a std::string. I can\'t seem to figure it out. Everything I\'ve tried gives me i

3条回答
  •  轮回少年
    2021-01-31 11:08

    Your code will expect a null-terminated string from the buffer you supply to the string constructor! Which means the result will almost certainly be wrong.

    To enforce the digest size and, use the following instead:

    return std::string((char*)abDigest, CryptoPP::SHA256::DIGESTSIZE);

    Also with respect to printing it the following correctly produces the test vector BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD for the string "abc"

    std::string string_to_hex(const std::string& input)
    {
      static const char* const lut = "0123456789ABCDEF";
      size_t len = input.length();
    
      std::string output;
      output.reserve(2 * len);
      for (size_t i = 0; i < len; ++i)
      {
        const unsigned char c = input[i];
        output.push_back(lut[c >> 4]);
        output.push_back(lut[c & 15]);
      }
      return output;
    }
    
    std::string SHA256(std::string data)
    {
      CryptoPP::byte const* pbData = (CryptoPP::byte*)data.data();
      unsigned int nDataLen = data.length();
      CryptoPP::byte abDigest[CryptoPP::SHA256::DIGESTSIZE];
    
      CryptoPP::SHA256().CalculateDigest(abDigest, pbData, nDataLen);
    
      // return string((char*)abDigest);  -- BAD!!!
      return std::string((char*)abDigest, CryptoPP::SHA256::DIGESTSIZE);
    }
    
    void test_cryptopp() {
      std::cout << string_to_hex(SHA256("abc")) << std::endl;
    }
    

提交回复
热议问题