简体   繁体   English

在C ++中将AES加密字符串转换为十六进制

[英]Convert AES encrypted string to hex in C++

I have a char* string that I have encoded using AES encryption. 我有一个char *字符串,我使用AES加密编码。 This string contains a wide range of hex characters, not just those viewable by ASCII. 此字符串包含各种十六进制字符,而不仅仅是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. 我需要转换这个字符串,以便我可以通过HTTP发送它,它不接受加密算法生成的所有字符。

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. 我使用了以下函数但是有很多空格(0xFF),它无法转换所有字符。

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. 我不知道c ++中是否有lib,但最好的方法是将字节编码为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. 首先,你的角色可能是签名的,这就是你获得大量FF的原因 - 如果你的角色是0x99,那么当打印时它会被符号扩展到0xFFFFFF99。 Second, strlen (or dStrlen - what is that?) is bad because your input string may have nulls in it. 第二,strlen(或dStrlen - 这是什么?)是不好的,因为你的输入字符串可能有空值。 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. 您可以使用各种库进行转换,例如: http//www.nuclex.org/downloads/developers/snippets/base64-encoder-and-decoder-in-cxx ,但它确实使字符串更大比原来的,因为它需要一个8位字符并将其转换为7位字符。

You will then need to decode it to be able to use it. 然后,您需要对其进行解码才能使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM