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 invalid output.
Here's the new code after interjay's answer:
string SHA256(string data) { byte const* pbData = (byte*) data.data(); unsigned int nDataLen = data.size(); byte abDigest[CryptoPP::SHA256::DIGESTSIZE]; CryptoPP::SHA256().CalculateDigest(abDigest, pbData, nDataLen); return string((char*)abDigest); }
The output for SHA256("A"); is
How can I turn this into a readable format?
Thanks to interjay's answer I was able to generate the final hash.
This outputs a base64 string using the CryptoPP::Base64Encoder
:
#include "sha.h" #include "filters.h" #include "base64.h" std::string SHA256HashString(std::string aString){ std::string digest; CryptoPP::SHA256 hash; CryptoPP::StringSource foo(aString, true, new CryptoPP::HashFilter(hash, new CryptoPP::Base64Encoder ( new CryptoPP::StringSink(digest)))); return digest; }
This line will give the wrong results:
unsigned int nDataLen = sizeof(pbData);
It will always give you the size of a pointer. What you want instead is data.size()
.
Also, you don't need this part:
if(!CryptoPP::SHA256().VerifyDigest(abDigest, pbData, nDataLen)) { return SHA256(data); }
It should always verify correctly, since you just calculated the digest based on the same data. And if it didn't, you'd go into infinite recursion.
To get readable output, you can convert it to hex. Here's an example for MD5 from the Crypto++ Wiki, it should work for you if you replace MD5 with SHA256:
CryptoPP::MD5 hash; byte digest[ CryptoPP::MD5::DIGESTSIZE ]; std::string message = "abcdefghijklmnopqrstuvwxyz"; hash.CalculateDigest( digest, (byte*) message.c_str(), message.length() ); CryptoPP::HexEncoder encoder; std::string output; encoder.Attach( new CryptoPP::StringSink( output ) ); encoder.Put( digest, sizeof(digest) ); encoder.MessageEnd(); std::cout << output << std::endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With