我有以下代码将加密的密文转换为可读的十六进制格式:
std::string convertToReadable(std::string ciphertext)
{
std::stringstream outText;
for(unsigned int i = 0; i < ciphertext.size(); i++ )
outText << std::hex << std::setw(2) << std::setfill('0') << (0xFF & static_cast<byte>(ciphertext[i])) << ":";
return outText.str();
}
Run Code Online (Sandbox Code Playgroud)
该函数的可读结果如下:
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:
Run Code Online (Sandbox Code Playgroud)
现在我需要回过头来,将可读格式转换为原始格式ciphertext以便解密它:
std::string convertFromReadable(std::string text)
{
std::istringstream cipherStream;
for(unsigned int i = 0; i < 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();
}
Run Code Online (Sandbox Code Playgroud)
这不是绝对有效的,因为我得到了错误的字符串.
我怎样才能解决这个问题,convertFromReadable()以便我可以拥有原始版本ciphertext?
谢谢你的帮助
以下是在进一步调试之前应该修复的问题:
cipherStream应该是ostringstream,不是istringstreamfor循环结束前应停止两个字符.否则你substr会失败.制作循环条件i+2 < text.size()i两个,即在行i++后添加std::string str = text.substr(i, 2);.char在将数据写入时添加强制转换cipherStream,即cipherStream << (char)value| 归档时间: |
|
| 查看次数: |
252 次 |
| 最近记录: |