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

Doug picture Doug · May 8, 2011 · Viewed 27.3k times · Source

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

enter image description here

How can I turn this into a readable format?

Thanks to interjay's answer I was able to generate the final hash.

Answer

Rooke picture Rooke · Aug 12, 2011

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;
}