how to make crypto
Generating a Cryptographic Hash in C++
#include <iostream>
#include <openssl/sha.h>
#include <iomanip>
#include <sstream>
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 data = "hello world";
std::string hash = sha256(data);
std::cout << "SHA-256 hash of 'hello world': " << hash << std::endl;
return 0;
}
- Include necessary libraries:
#include <iostream>
for input/output operations#include <openssl/sha.h>
for SHA-256 hashing algorithm#include <iomanip>
for manipulation of output format#include <sstream>
for string stream processingDefine a function to calculate SHA-256 hash:
- Create a function
sha256
that takes a string as input and returns its SHA-256 hash as a string. - Use
SHA256_CTX
andSHA256_Init
to initialize the SHA-256 context. - Use
SHA256_Update
to update the context with the input string. - Use
SHA256_Final
to finalize the hash calculation and store the result in thehash
array. Format the hash array into a string using
std::stringstream
and return it.Implement the main function:
- Define the
main
function. - Set a test string
data
to "hello world". - Calculate the SHA-256 hash of
data
using thesha256
function. - Output the hash to the console.
This code snippet demonstrates how to generate a SHA-256 cryptographic hash in C++ using the OpenSSL library.