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
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).
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;
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.