I'm trying to convert Hexadecimal string to binary, which will be passed to encryption Library later (openssl AES EVP_xx), so i guess i just need a Binary string with nul teminator.
I've used 2nd test demonstrated by Josch His Test case is pretty powerful, so I'm ending up using lookup table. I'm Just changed the input variables and added printing but alwys get garbage printed.
I've only added the following:
malloc (expected binary string length + 1)
set the nul terminator at the end of the loop. AFAIK these garbage character returned when string is not null terminated.
#include <string.h> #include <stdio.h> #include <stdlib.h> /* the resulting binary string is half the size of the input hex string * because every two hex characters map to one byte */ unsigned char base16_decoding_table1[256] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0,0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}; int main(int argc, char **argv){ int TESTDATALEN=strlen(( char*) argv[1]); //char *result=malloc((TESTDATALEN/2)+1); int mallocLen=(TESTDATALEN%2) ? ((TESTDATALEN+3)/2) : ((TESTDATALEN/2)+1); unsigned char *result=malloc(mallocLen); *result='\0'; int i; unsigned char cur; unsigned char val; for (i = 0; i < TESTDATALEN; i++) { cur = argv[1][i]; val = base16_decoding_table1[(int)cur]; /* even characters are the first half, odd characters the second half * of the current output byte */ if (i%2 == 0) { result[i/2] = val << 4; } else { result[i/2] |= val; } } result[mallocLen] = '\0'; printf ("Binary value: %s\n", result); //for (i = 0; i < TESTDATALEN/2; i++) printf ("%02hhx", result[i]); //putchar ('\n'); free(result); return 0; }
I might add more to the context if it's relevant; i can't touch strcat for performance reasons since the hexadecimal to binary is just one step in the encryption which is performed on thousand (or milllions) of input, the single field can reach 8kb so can't use strtol either and have to do it in strings,
Current output is:
hex2bin1.6.2 abc123def789
��#�
While Binary equivalent for this value is: 101010111100000100100011110111101111011110001001
The target is feed this binary string returned from this conversion code to openssl AES EVP encryption routines, which accepts and returns binary input.
Thanks in advance