SHA-256 Implementation

Show the SHA-256 inplementation in C++.

Note: Linux kernel is needed.

This is an algorithm with only SHA-256 used.

#include <openssl/sha.h>
using namespace std;

string sha256(const string &code) {
  char buf[2];
  unsigned char hash[SHA256_DIGEST_LENGTH];
  SHA256_CTX sha256;
  SHA256_Init(&sha256);
  SHA256_Update(&sha256, code.c_str(), code.size());
  SHA256_Final(hash, &sha256);
  string key;
  for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
    snprintf(buf, 2, "%02x", hash[i]);
    key += buf;
  }
  return key;
}

The algorithm below is more complicated.

#include <openssl/sha.h>
using namespace std;

string processCode(const string &code) {
  string key = code;
  char buf[2];
  unsigned char hash[SHA256_DIGEST_LENGTH], pos = 0;
  for (auto &i : code)
    pos += i;
  SHA256_CTX sha256;
  SHA256_Init(&sha256);
  for (int i = 0; i < pos % 10 + 1; i++) {
    SHA256_Update(&sha256, key.c_str(), key.size());
    SHA256_Final(hash, &sha256);
    key.clear();
    for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
      snprintf(buf, 2, "%02x", hash[i]);
      key += buf;
    }
  }
  for (auto &i : key)
    i -= pos;
  return key;
}