tags:

views:

203

answers:

3

Hello,

I have a char* string that I have encoded using AES encryption. This string contains a wide range of hex characters, not just those viewable by ASCII. I need to convert this string so I can send it through HTTP, which does not accept all of the characters generated by the encryption algorithm.

What is the best way to convert this string? I have used the following function but there are a lot of blanks (0xFF), it cant convert all of the 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;
}

Thank you, Justin

+10  A: 

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

Noon Silk
+1 - a very simple solution to use base64. I had to do this before in order to store keys in an xml file.
James Black
http://libb64.sourceforge.net/
Stobor
A: 

There are various libraries you can use to do the conversion, such as: http://www.nuclex.org/downloads/developers/snippets/base64-encoder-and-decoder-in-cxx, but it does make the string bigger than the original, since it takes an 8 bit character and converts it to be a 7 bit character.

You will then need to decode it to be able to use it.

James Black
+3  A: 

A few problems. First, your characters are probably signed, which is why you get lots of FF's - if your character was 0x99, then it gets sign extended to 0xFFFFFF99 when printed. Second, strlen (or dStrlen - what is that?) is bad because your input string may have nulls in it. You need to pass around the string length explicitly.

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;
}
Keith Randall
Nice catch on the signed char problem and you beat me to the punch on the problem about treating the ciphertext as a C-style string.
Michael Burr