使用openssl和C ++生成sha256 [英] generate sha256 with openssl and C++
本文介绍了使用openssl和C ++生成sha256的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用sha256使用openssl和C ++创建一个散列。我知道这里有一个类似的帖子:
生成sha哈希在openssl ,但我正在寻找专门创建sha256。
更新:
似乎是包含路径的问题。它不能找到任何openssl函数,即使我包括
#includeopenssl / sha.h
我在我的生成中包含了路径
-I / opt / ssl / include / -L / opt / ssl / lib / -lcrypto
解决方案这是我做的:
void sha256 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{
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;
字节散列[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;
}
这样调用:
$ b bstatic unsigned char buffer [65];
sha256(string,buffer);
printf(%s\\\
,buffer);
I'm looking to create a hash with sha256 using openssl and C++. I know there's a similar post about this here:
generate sha hash in openssl, but I'm looking to specifically create sha256.
UPDATE:
Seems to be a problem witht he 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
解决方案Here's how I did it:
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; }
It's called like this:
static unsigned char buffer[65]; sha256("string", buffer); printf("%s\n", buffer);
这篇关于使用openssl和C ++生成sha256的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文