MinitScript  0.9.31 PRE-BETA
SHA256.cpp
Go to the documentation of this file.
1 #include <openssl/sha.h>
2 
3 #include <string>
4 #include <vector>
5 #include <cstring>
6 
9 
11 
12 using std::string;
13 using std::vector;
14 
15 void SHA256::encode(const string& decodedString, string& encodedString) {
16  hash((const uint8_t*)decodedString.data(), decodedString.size(), encodedString);
17 }
18 
19 void SHA256::encode(const vector<uint8_t>& decodedData, string& encodedString) {
20  hash(decodedData.data(), decodedData.size(), encodedString);
21 }
22 
23 inline void SHA256::hash(const uint8_t* data, size_t size, string& encodedString) {
24  // see: https://stackoverflow.com/questions/2262386/generate-sha256-with-openssl-and-c
25  // check this later: https://stackoverflow.com/questions/34289094/alternative-for-calculating-sha256-to-using-deprecated-openssl-code
26  unsigned char hash[SHA256_DIGEST_LENGTH];
27  SHA256_CTX sha256;
28  SHA256_Init(&sha256);
29  SHA256_Update(&sha256, data, size);
30  SHA256_Final(hash, &sha256);
31  char outputBuffer[SHA256_DIGEST_LENGTH * 2 + 1];
32  outputBuffer[SHA256_DIGEST_LENGTH * 2] = 0;
33  for (int64_t i = 0; i < SHA256_DIGEST_LENGTH; i++) {
34  snprintf(outputBuffer + (i * 2), 3, "%02x", hash[i]);
35  }
36  encodedString = string(outputBuffer, SHA256_DIGEST_LENGTH * 2);
37 }
SHA256 hash class.
Definition: SHA256.h:16
static void hash(const uint8_t *data, size_t size, string &encodedString)
Hashes data to SHA256 string.
Definition: SHA256.cpp:23
static const string encode(const string &decodedString)
Encodes an string to SHA256 string.
Definition: SHA256.h:23