What I'm trying to do
The MD5 function from the crypto library of OpenSSL (as well as many other its hash functions) returns an array of unsigned char
. I'm trying to get a hash string from this array.
Example:
Array:
{126, 113, 177, 57, 8, 169, 240, 118, 60, 10, 229, 74, 249, 6, 32, 128}
Hash:
7e71b13908a9f0763c0ae54af9062080
Each number in the array is represented as two hexadecimal digits. And the length of a hash string is twice as great as the length of the array.
What I have got
Please see the full code here. Here is a part of it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define nu 0
typedef struct {
int len;
unsigned char *Hash;
}Type;
Type test[6];
int main(void) {
unsigned char XUzQ[16]={
126, 113, 177, 57, 8, 169, 240, 118, 60, 10, 229, 74, 249, 6, 32, 128
};
test[0].len=16; test[0].Hash=XUzQ;
int h;
const char *hex="0123456789abcdef";
char *Ha=calloc(test[nu].len*2+1,sizeof(char));
for (h=0;h<test[nu].len;++h) {
*(++Ha)=hex[(test[nu].Hash[h]/16)%16];
*(++Ha)=hex[test[nu].Hash[h]%16];
}
Ha-=(test[nu].len*2-1);
if (strlen(Ha)==(test[nu].len*2))
printf("'%s'\n",Ha);
else puts("Failed!");
Ha--;
free(Ha);
return 0;
}
This prints the value I expect (7e71b13908a9f0763c0ae54af9062080
), but to my mind, the same thing could be implemented better and faster.
Notes
The names of the arrays I'm working with are so strange as they were auto-generated by my Python script using random characters.
test
is intended to be an array that big (please see my full code by clicking the link above).
Question
How could I achieve the same result faster and easier? I'd be grateful if the solution supported all hashing algorithms that are supported by OpenSSL.