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:
cipherstreamshouldostringstream, notistringstream- the
forloop should stop 2 characters before end. otherwisesubstrgoing fail. make loop conditioni+2 < text.size() - when read 2 characters input, need advance
itwo, i.e. addi++afterstd::string str = text.substr(i, 2);line. - since want character output, add cast
charwhen writing datacipherstream, i.e.cipherstream << (char)value
Comments
Post a Comment