Sha256 Hashes in Cilk

Here’s the translation of the SHA256 Hashes example from Go to Cilk, formatted in Markdown suitable for Hugo:

#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#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();
}

cilk_int main() {
    std::string s = "sha256 this string";
    
    std::string hash = sha256(s);
    
    std::cout << s << std::endl;
    std::cout << hash << std::endl;
    
    return 0;
}

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 Cilk.

Cilk doesn’t have built-in cryptographic functions, so we’re using the OpenSSL library to perform the SHA256 hash. We include the necessary headers and define a helper function sha256 that takes a string and returns its SHA256 hash as a hexadecimal string.

In the main function:

  1. We start by defining the string we want to hash.
  2. We call our sha256 function to compute the hash.
  3. Finally, we print both the original string and its hash.

To run the program, you would compile it with Cilk compiler and link against the OpenSSL library:

$ cilk++ -o sha256_hashes sha256_hashes.cpp -lcrypto
$ ./sha256_hashes
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

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

Also, remember that Cilk is an extension of C++, so it supports all C++ features along with its own parallel constructs. In this example, we didn’t use any Cilk-specific features, but in more complex scenarios, you could leverage Cilk’s parallel programming capabilities for hash computations on large datasets.