Skip to content

Instantly share code, notes, and snippets.

@kotlinsyntax
Created March 30, 2024 18:44
Show Gist options
  • Save kotlinsyntax/835e6af41ef457d5c85655f76abbd91d to your computer and use it in GitHub Desktop.
Save kotlinsyntax/835e6af41ef457d5c85655f76abbd91d to your computer and use it in GitHub Desktop.
Sha256 Implementation in C++
#include <cstdint>
#include <string>
#include <sstream>
#include <iomanip>
uint32_t rotateLeft(uint32_t x, uint32_t n) {
return (x << n) | (x >> (32 - n));
}
std::string sha256(const std::string& input) {
uint32_t hash_values[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
std::string padded_input = input + '\x80';
size_t original_length = input.length(), padding_length = (64 - (original_length + 8) % 64) % 64;
padded_input += std::string(padding_length, '\x00') + std::string(reinterpret_cast<const char*>(&original_length), 8);
for (size_t i = 0; i < padded_input.length(); i += 64) {
const auto* chunk = reinterpret_cast<const uint32_t*>(&padded_input[i]);
uint32_t a = hash_values[0], b = hash_values[1], c = hash_values[2], d = hash_values[3], e = hash_values[4], f = hash_values[5], g = hash_values[6], h = hash_values[7];
for (int j = 0; j < 64; ++j) {
uint32_t temp1 = h + rotateLeft(e, 6) + ((e & f) ^ (~e & g)) + chunk[j];
uint32_t temp2 = rotateLeft(a, 2) + ((a & b) ^ (a & c) ^ (b & c));
h = g; g = f; f = e; e = d + temp1; d = c; c = b; b = a; a = temp1 + temp2;
}
for (int k = 0; k < 8; ++k) hash_values[k] += (k == 0) ? a : (k == 1) ? b : (k == 2) ? c : (k == 3) ? d : (k == 4) ? e : (k == 5) ? f : (k == 6) ? g : h;
}
std::stringstream ss;
for (unsigned int i : hash_values) ss << std::hex << std::setw(8) << std::setfill('0') << i;
return ss.str();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment