Why is this SHA256 function printing some weird characters?
This is the code
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <byteswap.h>
#include "/usr/include/openssl/sha.h"
#include <evhttp.h>
bool hex2bin(unsigned char *p, const char *hexstr, size_t len);
bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
{
while (*hexstr && len) {
char hex_byte[3];
unsigned int v;
if (!hexstr[1]) {
//applog(LOG_ERR, "hex2bin str truncated");
return false;
开发者_开发问答 }
hex_byte[0] = hexstr[0];
hex_byte[1] = hexstr[1];
hex_byte[2] = 0;
if (sscanf(hex_byte, "%x", &v) != 1) {
//applog(LOG_ERR, "hex2bin sscanf '%s' failed",
//hex_byte);
return false;
}
*p = (unsigned char) v;
p++;
hexstr += 2;
len--;
}
return (len == 0 && *hexstr == 0) ? true : false;
}
int main(int argc, char **argv)
{
unsigned char hash[SHA256_DIGEST_LENGTH], hash1[SHA256_DIGEST_LENGTH];
uint32_t *hash32 = (uint32_t *) hash;
unsigned char data[128];
uint32_t *data32 = (uint32_t *) data;
int i;
hex2bin(data, argv[1], sizeof(data));
for (i = 0; i < 128/4; i++)
data32[i] = bswap_32(data32[i]);
SHA256(data, 80, hash1);
SHA256(hash1, SHA256_DIGEST_LENGTH, hash);
printf("%s\n\n",hash1);
return 0;
}
Sorry for the long code. Also, don't mind the unnecessary includes, i just wasn't sure which were needed so i compiled regardless.
This is written in C(obviously) running under Linux, Ubuntu 11.04.
This program takes as an argument some string and must compute it's sha256 hash(twice, while doing various stuff before actually hashing it). Although the program compiles,runs and takes the string, it spews some weird characters instead of a hash. Why so?
P.S This code is not mine, i just made it into a separate program for myself, but like i said, printing the hash fails with some weird characters!
P.S2 SHA256 is defined in the LibSSL's libcrypto library. The program is compiled with the -lcrypto argument using gcc.
The output of a hash is almost always opaque binary data - i.e. any bytes.
You're trying to print those as if they were text. That means it'll be applying some encoding to the binary data, trying to interpret it as text.
Basically you should use the opposite of hex2bin
in order to convert the arbitrary binary data into hex.
精彩评论