The #1 rule of cryptography: Don’t invent your own!
OK wiseman, now what? You want to add crypto to your program but you don’t want to code it all yourself. I’ll show you three libraries that make it possible. The choice will be yours as to which one to use.
For this example, I wanted to write a simple function that accepts a...
std::string
...message and returns hex encoded SHA-1 hash. I picked the following libraries: Crypto++, WolfSSL, and Botan. All three made it pretty easy, and I don’t want to get into the business of picking winners and losers, but… Botan made it a breeze and I think it will be my choice going forward.
crypto.cpp:
#include <iostream>
#include <sstream>
#include <string>
#include <cryptopp/cryptlib.h>
#include <cryptopp/sha.h>
#include <cryptopp/hex.h>
#include <cryptopp/files.h>
#include <wolfssl/wolfcrypt/sha.h>
#include <botan-2/botan/hash.h>
#include <botan-2/botan/hex.h>
using namespace std;
string Hash_CryptoPP(const string& msg)
{
CryptoPP::SHA1 hash;
std::string digest(hash.DigestSize(), '*');
stringstream output;
hash.Update((const CryptoPP::byte*)msg.data(), msg.size());
hash.Final((CryptoPP::byte*)&digest[0]);
CryptoPP::HexEncoder encoder(new CryptoPP::FileSink(output));
CryptoPP::StringSource(digest, true, new CryptoPP::Redirector(encoder));
return output.str();
}
string Hash_WolfSSL(const string& msg)
{
Sha sha;
::byte shaSum[SHA_DIGEST_SIZE];
stringstream output;
wc_InitSha(&sha);
wc_ShaUpdate(&sha, (::byte*)msg.data(), msg.length());
wc_ShaFinal(&sha, shaSum);
string digest(shaSum, shaSum + SHA_DIGEST_SIZE);
CryptoPP::HexEncoder encoder(new CryptoPP::FileSink(output));
CryptoPP::StringSource(digest, true, new CryptoPP::Redirector(encoder));
return output.str();
}
string Hash_Botan(const string& msg)
{
auto hash = Botan::HashFunction::create("SHA-1");
hash->update((uint8_t*)msg.data(), msg.length());
return Botan::hex_encode(hash->final());
}
int main()
{
std::string msg = "Vorbrodt's C++ Blog @ https://vorbrodt.blog";
cout << "Message: " << msg << endl;
cout << "Digest : " << Hash_CryptoPP(msg) << endl << endl;
cout << "Message: " << msg << endl;
cout << "Digest : " << Hash_WolfSSL(msg) << endl << endl;
cout << "Message: " << msg << endl;
cout << "Digest : " << Hash_Botan(msg) << endl << endl;
}
Program output:
Message: Vorbrodt’s C++ Blog @ https://vorbrodt.blog
Digest : 24BCAC1359AA8B773D38D6A05B22BB43DAB5B8E5
Message: Vorbrodt’s C++ Blog @ https://vorbrodt.blog
Digest : 24BCAC1359AA8B773D38D6A05B22BB43DAB5B8E5
Message: Vorbrodt’s C++ Blog @ https://vorbrodt.blog
Digest : 24BCAC1359AA8B773D38D6A05B22BB43DAB5B8E5