2010-02-14 27 views
49

Estoy buscando crear un hash con sha256 usando openssl y C++. Sé que hay una publicación similar en Generate SHA hash in C++ using OpenSSL library, pero estoy buscando específicamente crear sha256.Generar sha256 con OpenSSL y C++

UPDATE:

parece ser un problema con los caminos incluir. No se puede encontrar ninguna función OpenSSL a pesar de que he incluido

#include "openssl/sha.h" 

e incluí los caminos en mi construcción

-I/opt/ssl/include/ -L/opt/ssl/lib/ -lcrypto 
+0

También como una bonificación, sería bueno si fuera el hash en binario :) –

+1

He publicado una nueva respuesta que explica lo que quieres. Puede cerrar esta pregunta como duplicada si esa respuesta ayuda. – AndiDog

+0

@AndiDog - Todo parece funcionar bien, excepto que el compilador no puede encontrar las funciones. Ni siquiera podía encontrar una referencia a SHA1. Además, no se puede encontrar ninguna de las funciones de SHA256 como 'SHA256_Final '. No estoy seguro de lo que estoy haciendo mal, incluí #include "openssl/sha.h" e incluí el include y la biblioteca durante la compilación -I/opt/ssl/include/-L/opt/ssl/lib/-lcrypto –

Respuesta

58

Así es como lo hice:

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; 
} 

es c alled como esto:

static unsigned char buffer[65]; 
sha256("string", buffer); 
printf("%s\n", buffer); 
+1

Hola, para todos los que usan el gran QT :) - También puedes usar esto , solo agregue a su archivo de proyecto 'LIBS + = - lcrypto' y luego simplemente convierta el código a una clase y todo funcionará bien;) – TCB13

+3

-1:" SHA1_Init(), SHA1_Update() y SHA1_Final() return 1 para el éxito, 0 de lo contrario ", http://www.openssl.org/docs/crypto/sha.htm. – jww

+0

@noloader Irrelevante ya que estas funciones no se usan aquí. –

1

creo que es suficiente para reemplazar la función SHA1 con la función SHA256 con código tatk desde el enlace en tu mensaje

2

A más "C++" versión 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; 
} 
+1

-1: "SHA1_Init(), SHA1_Update() y SHA1_Final() return 1 para el éxito, 0 en caso contrario ", openssl.org/docs/crypto/sha.htm. – jww

+3

no quería oscurecer el código con las comprobaciones de valor de retorno estilo C. Bricolaje si te importa – Max

+9

"Bricolaje si te importa" - disculpa que te moleste. La gente lo copiará/pegará a ciegas. Ignorar los valores de retorno es una práctica peligrosa, y no debe demostrarse (especialmente en código de alta integridad). – jww

30

std basado

#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

No lo he probado, pero definitivamente parece más limpio que todas las demás versiones de "C++". –

+4

Este código compila y produce el resultado esperado. En ubuntu, puede usar: sudo apt-get install libssl-dev && g ++ -lcrypto main.cc para compilarlo. – Homer6

+1

Esta solución es en realidad mejor que la aceptada, ya que ostringstream es mucho, mucho más seguro que jugar con arrays y 'sprintf'. – omni

5

Uso de OpenSSL EVP interface (lo siguiente es para OpenSSL 1,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_new(); 

    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_free(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; 
} 

La ventaja de esta interfaz de nivel superior es que simplemente necesita cambiar la llamada EVP_sha256() con la función de otro resumen, p. EVP_sha512(), para usar un resumen diferente. Entonces agrega cierta flexibilidad.