Gerar hash SHA em C++ com a biblioteca OpenSSL

Como posso gerar os traços SHA1 ou SHA2 usando oOpenSSL libarary?

procurei no google e não encontrei nenhuma função ou código de exemplo.

Author: Uli Köhler, 2009-05-28

4 answers

Da linha de comando, é simplesmente:

printf "compute sha1" | openssl sha1

Você pode invocar a biblioteca assim:

#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>

int main()
{
    unsigned char ibuf[] = "compute sha1";
    unsigned char obuf[20];

    SHA1(ibuf, strlen(ibuf), obuf);

    int i;
    for (i = 0; i < 20; i++) {
        printf("%02x ", obuf[i]);
    }
    printf("\n");

    return 0;
}

 72
Author: brianegge, 2013-05-20 19:12:55

O OpenSSL tem uma documentação horrível sem exemplos de código, mas aqui estás tu:

#include <openssl/sha.h>

bool simpleSHA256(void* input, unsigned long length, unsigned char* md)
{
    SHA256_CTX context;
    if(!SHA256_Init(&context))
        return false;

    if(!SHA256_Update(&context, (unsigned char*)input, length))
        return false;

    if(!SHA256_Final(md, &context))
        return false;

    return true;
}

Utilização:

unsigned char md[SHA256_DIGEST_LENGTH]; // 32 bytes
if(!simpleSHA256(<data buffer>, <data length>, md))
{
    // handle error
}

Depois disso, {[2] } conterá o código binário SHA-256. Código Similar pode ser usado para os outros membros da família SHA, basta substituir " 256 " no código.

Se tiver dados maiores, é claro que deve alimentar pedaços de dados à medida que chegam (múltiplas chamadas SHA256_Update).

 51
Author: AndiDog, 2018-05-22 08:21:35

A sintaxe correcta na linha de comandos deve ser

echo -n "compute sha1" | openssl sha1
Caso contrário, também vais atacar o personagem da nova linha.
 2
Author: mecano, 2011-04-29 21:58:07

Aqui é OpenSSL exemplo de cálculo sha-1 digest usando BIO:

#include <openssl/bio.h>
#include <openssl/evp.h>

std::string sha1(const std::string &input)
{
    BIO * p_bio_md  = nullptr;
    BIO * p_bio_mem = nullptr;

    try
    {
        // make chain: p_bio_md <-> p_bio_mem
        p_bio_md = BIO_new(BIO_f_md());
        if (!p_bio_md) throw std::bad_alloc();
        BIO_set_md(p_bio_md, EVP_sha1());

        p_bio_mem = BIO_new_mem_buf((void*)input.c_str(), input.length());
        if (!p_bio_mem) throw std::bad_alloc();
        BIO_push(p_bio_md, p_bio_mem);

        // read through p_bio_md
        // read sequence: buf <<-- p_bio_md <<-- p_bio_mem
        std::vector<char> buf(input.size());
        for (;;)
        {
            auto nread = BIO_read(p_bio_md, buf.data(), buf.size());
            if (nread  < 0) { throw std::runtime_error("BIO_read failed"); }
            if (nread == 0) { break; } // eof
        }

        // get result
        char md_buf[EVP_MAX_MD_SIZE];
        auto md_len = BIO_gets(p_bio_md, md_buf, sizeof(md_buf));
        if (md_len <= 0) { throw std::runtime_error("BIO_gets failed"); }

        std::string result(md_buf, md_len);

        // clean
        BIO_free_all(p_bio_md);

        return result;
    }
    catch (...)
    {
        if (p_bio_md) { BIO_free_all(p_bio_md); }
        throw;
    }
}

Embora seja mais longo do que apenas chamar a função SHA1 de OpenSSL, mas é mais universal e pode ser retrabalhada para usar com fluxos de arquivos (assim, processar dados de qualquer comprimento).

 1
Author: anton_rh, 2015-12-10 12:18:23