41 lines
1.6 KiB
C++
41 lines
1.6 KiB
C++
/**
|
|
* @brief This C++ program is designed to compute the SHA-256 hash of a user-provided string.
|
|
* Here's a breakdown of how it works:
|
|
* Prompts the user to enter a string.
|
|
* Reads the input string from the standard input (using getline).
|
|
* Calls the SHA256 function with the user-provided string and prints the resulting SHA-256 hash.
|
|
*
|
|
* @author Yavuz Sava (woose)
|
|
* @date 13/12/2024
|
|
*/
|
|
|
|
#include <iostream>
|
|
#include <openssl/sha.h>
|
|
#include <openssl/crypto.h>
|
|
#include <openssl/evp.h>
|
|
#include <sstream>
|
|
#include <iomanip>
|
|
using namespace std;
|
|
string SHA256(const string str)
|
|
{
|
|
unsigned char hash[SHA256_DIGEST_LENGTH]; // Initialize a new context for digest operations using the EVP API
|
|
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
|
|
EVP_DigestInit_ex(ctx, EVP_sha256(), NULL); // Set up the context to use the SHA-256 algorithm
|
|
EVP_DigestUpdate(ctx, str.c_str(), str.size()); // Update the digest with the input string's bytes
|
|
EVP_DigestFinal_ex(ctx, hash, NULL); // Finish computing the hash and store it in the 'hash' buffer
|
|
EVP_MD_CTX_free(ctx); // Free up the context used for digest operations
|
|
stringstream ss;
|
|
for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) // Convert each byte of the hash into a two-digit hexadecimal number
|
|
ss << hex << setw(2) << setfill('0') << (int)hash[i];
|
|
return ss.str();
|
|
}
|
|
int main()
|
|
{
|
|
string str;
|
|
cout << "Enter a string to encrypt: ";
|
|
getline(cin, str);
|
|
// Compute the SHA-256 hash of the input string
|
|
cout << "Encrypted string using SHA-256 algorithm: " << SHA256(str) << endl;
|
|
return 0;
|
|
}
|