我有两个字符串(char *),其中包含一些数据的十六进制表示。我需要将其转换为二进制字符串,然后将结果xor组合在一起。之后,我将该二进制结果转换为十六进制表示。
char * convertHexToBinaryString(char *alphabetString)
{
char* val= (char*)malloc(strlen(alphabetString)*sizeof(char));
char *pos = alphabetString;
size_t count = 0;
/* WARNING: no sanitization or error-checking whatsoever */
for(count = 0; count < strlen(alphabetString)/2; count++) {
sscanf(pos, "%2hhx", &val[count]);
pos += 2 * sizeof(char);
}
return val;
}
char hexDigitForNumber(char number)
{
switch (number) {
case 0:
return '0';
break;
case 1:
return '1';
break;
case 2:
return '2';
break;
case 3:
return '3';
break;
case 4:
return '4';
break;
case 5:
return '5';
break;
case 6:
return '6';
break;
case 7:
return '7';
break;
case 8:
return '8';
break;
case 9:
return '9';
break;
case 10:
return 'a';
break;
case 11:
return 'b';
break;
case 12:
return 'c';
break;
case 13:
return 'd';
break;
case 14:
return 'e';
break;
case 15:
return 'f';
break;
default:
return 'X';
break;
}
return 100;
}
char * convertBinaryToHexString(char *binData)
{
char *result = (char *)malloc(strlen(binData)*2);
int latestIndex = 0;
int szBd = strlen(binData);
for (int i = 0; i < strlen(binData); i++) {
unsigned char crt = binData[i];
result[latestIndex] = hexDigitForNumber(crt >> 4);
result[latestIndex +1] = hexDigitForNumber(crt % 16);
latestIndex +=2;
}
return result;
}
char * xorBinaryStrings(char *s1,char *s2)
{
int endPoint = (int)MIN(strlen(s1),strlen(s2));
char *result = (char *)malloc(endPoint * sizeof(char));
for (int i = 0; i<=endPoint; i++) {
result[i] = s1[i] ^ s2[i];
}
return result;
}
我尝试使用这样的函数:
char *s = "48656c6c6f20576f726c64"; // Hello world
char *k= "7375706572736563726574"; // super secret
char *hexPT = convertHexToBinaryString(s);
char *hexKey = convertHexToBinaryString(k);
char *result = xorBinaryStrings(hexKey, hexPT);
char *rs = convertBinaryToHexString(result);
问题是rs字符串是3b101c091d53320c0 ......什么时候应该是3b101c091d53320c000910 ... 如何使它忽略该空字符串终止符???
答案 0 :(得分:1)
问题在于您将任意二进制数据存储在内存区域中,然后要求C库将其视为字符串。更好的解决方案是将uint8_t
类型用于任意字节大小的数据,并分别跟踪数组中包含的字节数,例如:使用size_t
变量。