This code uses the OpenSSL library to compute the SHA256 hash of a given std::string
. Two variants are provided, one of them computing a binary hash (returning a std::array<uint8_t, 32>
), the other computing a hex hash (returning a std::string
).
#include <string> #include <openssl/sha.h> template<typename T> std::string convertToHex(const T& binaryResult) { std::ostringstream ss; ss << std::hex << std::setfill('0'); for (unsigned int i = 0; i < binaryResult.size(); ++i) { ss << std::setw(2) << static_cast<unsigned>(binaryResult.at(i)); } return ss.str(); } std::array<uint8_t, 32> computeSHA256(const std::string& input) { std::array<uint8_t, 32> hash{}; EVP_MD_CTX* mdctx = EVP_MD_CTX_new(); const EVP_MD* md = EVP_sha256(); EVP_DigestInit_ex(mdctx, md, nullptr); EVP_DigestUpdate(mdctx, input.c_str(), input.length()); EVP_DigestFinal_ex(mdctx, hash.data(), nullptr); EVP_MD_CTX_free(mdctx); return hash; } std::string computeSHA256Hex(const std::string& input) { auto hash = computeSHA256(input); return convertToHex(hash); }
Compile using
g++ -o main main.cpp -lcrypto -lssl