Генерировать sha256 с помощью openssl и С++
Я хочу создать хэш с помощью sha256 с помощью openssl и С++. Я знаю, что здесь есть похожие сообщения:
Сгенерировать SHA-хэш в С++ с использованием библиотеки OpenSSL, но я ищу специально для создания sha256.
ОБНОВЛЕНИЕ:
Кажется, проблема связана с включением путей. Он не может найти никаких функций openssl, хотя я включил
#include "openssl/sha.h"
и я включил пути в моей сборке
-I/opt/ssl/include/ -L/opt/ssl/lib/ -lcrypto
Ответы
Ответ 1
Вот как я это сделал:
void sha256(char *string, char outputBuffer[65])
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, string, strlen(string));
SHA256_Final(hash, &sha256);
int i = 0;
for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
}
outputBuffer[64] = 0;
}
int sha256_file(char *path, char outputBuffer[65])
{
FILE *file = fopen(path, "rb");
if(!file) return -534;
byte hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
const int bufSize = 32768;
byte *buffer = malloc(bufSize);
int bytesRead = 0;
if(!buffer) return ENOMEM;
while((bytesRead = fread(buffer, 1, bufSize, file)))
{
SHA256_Update(&sha256, buffer, bytesRead);
}
SHA256_Final(hash, &sha256);
sha256_hash_string(hash, outputBuffer);
fclose(file);
free(buffer);
return 0;
}
Он называется так:
static unsigned char buffer[65];
sha256("string", buffer);
printf("%s\n", buffer);
Ответ 2
std на основе
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
using namespace std;
#include <openssl/sha.h>
string sha256(const 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);
stringstream ss;
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
ss << hex << setw(2) << setfill('0') << (int)hash[i];
}
return ss.str();
}
int main() {
cout << sha256("1234567890_1") << endl;
cout << sha256("1234567890_2") << endl;
cout << sha256("1234567890_3") << endl;
cout << sha256("1234567890_4") << endl;
return 0;
}
Ответ 3
Использование OpenSSL EVP-интерфейса для OpenSSL 1.0.1:
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <openssl/evp.h>
bool computeHash(const std::string& unhashed, std::string& hashed)
{
bool success = false;
EVP_MD_CTX* context = EVP_MD_CTX_create();
if(context != NULL)
{
if(EVP_DigestInit_ex(context, EVP_sha256(), NULL))
{
if(EVP_DigestUpdate(context, unhashed.c_str(), unhashed.length()))
{
unsigned char hash[EVP_MAX_MD_SIZE];
unsigned int lengthOfHash = 0;
if(EVP_DigestFinal_ex(context, hash, &lengthOfHash))
{
std::stringstream ss;
for(unsigned int i = 0; i < lengthOfHash; ++i)
{
ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
}
hashed = ss.str();
success = true;
}
}
}
EVP_MD_CTX_destroy(context);
}
return success;
}
int main(int, char**)
{
std::string pw1 = "password1", pw1hashed;
std::string pw2 = "password2", pw2hashed;
std::string pw3 = "password3", pw3hashed;
std::string pw4 = "password4", pw4hashed;
hashPassword(pw1, pw1hashed);
hashPassword(pw2, pw2hashed);
hashPassword(pw3, pw3hashed);
hashPassword(pw4, pw4hashed);
std::cout << pw1hashed << std::endl;
std::cout << pw2hashed << std::endl;
std::cout << pw3hashed << std::endl;
std::cout << pw4hashed << std::endl;
return 0;
}
Для OpenSSL 1.1 вам нужно просто изменить EVP_MD_CTX_create()
на EVP_MD_CTX_new()
и изменить EVP_MD_CTX_destroy()
на EVP_MD_CTX_free()
, так как они были переименованы в них соответственно в 1.1.
Преимущество этого интерфейса более высокого уровня заключается в том, что вам просто нужно поменять вызов EVP_sha256()
с помощью другой функции дайджеста, например. EVP_sha512()
, чтобы использовать другой дайджест. Таким образом, он добавляет некоторую гибкость.
Ответ 4
Я думаю, что вам нужно только заменить функцию SHA1 функцией SHA256 с помощью кода tatk из ссылки в вашем сообщении
Ответ 5
Более "С++" версия ish
#include <iostream>
#include <sstream>
#include "openssl/sha.h"
using namespace std;
string to_hex(unsigned char s) {
stringstream ss;
ss << hex << (int) s;
return ss.str();
}
string sha256(string line) {
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, line.c_str(), line.length());
SHA256_Final(hash, &sha256);
string output = "";
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
output += to_hex(hash[i]);
}
return output;
}
int main() {
cout << sha256("hello, world") << endl;
return 0;
}