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;
}
  1. Include necessary libraries:
  2. #include <iostream> for input/output operations
  3. #include <openssl/sha.h> for SHA-256 hashing algorithm
  4. #include <iomanip> for manipulation of output format
  5. #include <sstream> for string stream processing

  6. Define a function to calculate SHA-256 hash:

  7. Create a function sha256 that takes a string as input and returns its SHA-256 hash as a string.
  8. Use SHA256_CTX and SHA256_Init to initialize the SHA-256 context.
  9. Use SHA256_Update to update the context with the input string.
  10. Use SHA256_Final to finalize the hash calculation and store the result in the hash array.
  11. Format the hash array into a string using std::stringstream and return it.

  12. Implement the main function:

  13. Define the main function.
  14. Set a test string data to "hello world".
  15. Calculate the SHA-256 hash of data using the sha256 function.
  16. Output the hash to the console.

This code snippet demonstrates how to generate a SHA-256 cryptographic hash in C++ using the OpenSSL library.