Sha256 Hashes in C++

Here’s the translation of the SHA256 Hashes example to C++, formatted in Markdown suitable for Hugo:

SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature. Here’s how to compute SHA256 hashes in C++.

#include <iostream>
#include <iomanip>
#include <sstream>
#include <openssl/sha.h>

std::string sha256(const std::string& str) {
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, str.c_str(), str.size());
    SHA256_Final(hash, &sha256);
    std::stringstream ss;
    for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
    }
    return ss.str();
}

int main() {
    std::string s = "sha256 this string";

    // Here we compute the hash
    std::string hash = sha256(s);

    std::cout << s << std::endl;
    std::cout << hash << std::endl;

    return 0;
}

C++ doesn’t have built-in cryptographic functions in its standard library. In this example, we’re using the OpenSSL library to compute SHA256 hashes.

We define a function sha256 that takes a string as input and returns the SHA256 hash as a hexadecimal string.

In the main function, we create a string to hash, compute its hash using our sha256 function, and then print both the original string and its hash.

To compile and run this program, you’ll need to have OpenSSL installed and link against it:

$ g++ -o sha256-hashes sha256-hashes.cpp -lcrypto
$ ./sha256-hashes
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

You can compute other hashes using a similar pattern to the one shown above. For example, to compute SHA512 hashes, you would use the SHA512_* functions from OpenSSL instead.

Note that if you need cryptographically secure hashes, you should carefully research hash strength!