Convert AES encrypted string to hex in C ++

I have a char * string that I have encoded using AES encryption. This string contains a wide range of hexadecimal characters, not just the ones that can be viewed with ASCII. I need to convert this string so that I can send it over HTTP, which does not accept all characters generated by the encryption algorithm.

What's the best way to convert this string? I have used the following function, but there are many spaces (0xFF), it cannot convert all characters.

char *strToHex(char *str){
   char *buffer = new char[(dStrlen(str)*2)+1];
   char *pbuffer = buffer;
   int len = strlen( str );
   for(int i = 0; i < len ; ++i ){
      sprintf(pbuffer, "%02X", str[i]);
      pbuffer += 2;
   }
   return buffer;
}

      

Thanks Justin

+2


source to share


3 answers


Several problems. First, your characters are probably signed, so you get a lot of FF - if your character was 0x99, then when printed, it gets signed to 0xFFFFFF99. Second, strlen (or dStrlen - what is that?) Is bad because your input string might have zeros. You must explicitly pass the length of the string.



char *strToHex(unsigned char *str, int len){
  char *buffer = new char[len*2+1];
  char *pbuffer = buffer;
  for(int i = 0; i < len ; ++i ){
    sprintf(pbuffer, "%02X", str[i]);
    pbuffer += 2;
  }
  return buffer;
}

      

+5


source


I don't know if there is a lib in C ++ for it, but the best way is to base64 encode the bytes. It's pretty trivial to write your own coder if there is no standard around (but I suspect there will be one).



+10


source


There are various libraries you can use for the conversion, for example: http://www.nuclex.org/downloads/developers/snippets/base64-encoder-and-decoder-in-cxx , but it makes the string look more original since it takes an 8 bit character and converts it to a 7 bit character.

Then you will need to decrypt it in order to use it.

0


source







All Articles