使用 OpenSSL 和 C++ 生成 sha256 [英] Generate sha256 with OpenSSL and C++

查看:99
本文介绍了使用 OpenSSL 和 C++ 生成 sha256的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用 openssl 和 C++ 创建一个带有 sha256 的哈希.我知道在 使用 OpenSSL 库在 C++ 中生成 SHA 哈希 上有一个类似的帖子,但我正在寻找专门创建 sha256.

I'm looking to create a hash with sha256 using openssl and C++. I know there's a similar post at Generate SHA hash in C++ using OpenSSL library, but I'm looking to specifically create sha256.

更新:

似乎是包含路径的问题.即使我包含了

Seems to be a problem with the include paths. It can't find any OpenSSL functions even though I included

#include "openssl/sha.h"

并且我在构建中包含了路径

and I included the paths in my build

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

推荐答案

我是这样做的:

void sha256_hash_string (unsigned char hash[SHA256_DIGEST_LENGTH], char outputBuffer[65])
{
    int i = 0;

    for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
    {
        sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
    }

    outputBuffer[64] = 0;
}


void sha256_string(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;

    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    const int bufSize = 32768;
    unsigned char *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
", buffer);

这篇关于使用 OpenSSL 和 C++ 生成 sha256的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆