问题
I´m using SHA512 in C to get an Hash-Value. I did it like this:
#include <stdlib.h>
#include <stdio.h>
#include <openssl/sha.h>
int main(int argc, char *argv[]){
unsigned char hash[SHA512_DIGEST_LENGTH];
char data[] = "data to hash"; //Test Data
SHA512(data, sizeof(data) - 1, hash); //Kill termination character
//Now there is the 64byte binary in hash
I tried to convert it to hex by:
long int binaryval, hexadecimalval = 0, i = 1, remainder;
binaryval=(long int)hash;
while (binaryval != 0)
{
remainder = binaryval % 10;
hexadecimalval = hexadecimalval + remainder * i;
i = i * 2;
binaryval = binaryval / 10;
}
printf("Outpunt in Hex is: %lX \n", hexadecimalval);
printf("%d\n",(long int) awhash );
return 0;
}
But this is not wat i wantet.
How can i convert the binary which is in a unsigned char into a human readable format? Best case in a char[] for printing.
The Hash for "data to hash" should be:
d98f945fee6c9055592fa8f398953b3b7cf33a47cfc505667cbca1adb344ff18a4f442758810186fb480da89bc9dfa3328093db34bd9e4e4c394aec083e1773a
回答1:
Just print each char using %x in a printf(). Don't convert, just use the raw data:
int main(int argc, char *argv[]){
unsigned char hash[SHA512_DIGEST_LENGTH];
char data[] = "data to hash"; //Test Data
SHA512(data, sizeof(data) - 1, hash); //Kill termination character
//Now there is the 64byte binary in hash
for(int i=0; i<64; i++)
{
printf("%02x", hash[i]);
}
printf("\n");
}
Edited to just output the hex value no commas or spaces.
来源:https://stackoverflow.com/questions/47702475/how-to-convert-a-raw-64-byte-binary-to-hex-or-ascii-in-c