encryption - c++ convert hexadecimal string with ":" to original "binary" string -


i have following code convert encrypted ciphertext readable hexadecimal format:

std::string converttoreadable(std::string ciphertext) {     std::stringstream outtext;      for(unsigned int = 0; < ciphertext.size(); i++ )         outtext << std::hex << std::setw(2) << std::setfill('0') << (0xff & static_cast<byte>(ciphertext[i])) << ":";      return outtext.str(); } 

the readable result of function as:

56:5e:8b:a8:04:93:e2:f1:5c:20:8b:fd:f5:b7:22:0b:82:42:46:58:9b:d4:c1:8e:ac:62:85:04:ff:7f:c6:d3: 

now need way back, converting readable format original ciphertext in order decrypt it:

std::string convertfromreadable(std::string text) {     std::istringstream cipherstream;      for(unsigned int = 0; < text.size(); i++ )     {         if (text.substr(i, 1) == ":")             continue;          std::string str = text.substr(i, 2);         std::istringstream buffer(str);         int value;         buffer >> std::hex >> value;         cipherstream << value;     }      return cipherstream.str(); } 

this not absolutely working, i´m getting wrong string back.

how can fix convertfromreadable() can have original ciphertext ?

thanks helping

here problems should fix before debugging further:

  • cipherstream should ostringstream, not istringstream
  • the for loop should stop 2 characters before end. otherwise substr going fail. make loop condition i+2 < text.size()
  • when read 2 characters input, need advance i two, i.e. add i++ after std::string str = text.substr(i, 2); line.
  • since want character output, add cast char when writing data cipherstream, i.e. cipherstream << (char)value

Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Website Login Issue developed in magento -

Can the constants be defined inside a model file of a framework in PHP? -