2015-06-04 49 views
4

我有以下代碼來加密的密文轉換成可讀的十六進制格式:C++轉換十六進制字符串用「:」,以原來的「二進制」串

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(); 
} 

此函數的可讀的結果是一些爲:

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: 

現在我需要做回來的路上,爲了可讀格式轉換爲原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(); 
} 

這不是絕對的工作,因爲我錯了字符串回來。

我該如何修復convertFromReadable(),以便我可以回到原來的ciphertext

感謝您的幫助

+0

你聽說過'const'和引用 –

+0

值得擁有的LOOKAT「位集」 – 911

+1

ED,請明確闡述你的觀點.. – Mendes

回答

5

下面是你應該任何進一步的調試在此之前解決問題:

  • cipherStreamostringstream,不istringstream
  • for循環應該結束前停止兩個字符。否則您的substr將會失敗。創建循環條件i+2 < text.size()
  • 當您從輸入中讀取兩個字符時,需要先將i提前兩位,即在std::string str = text.substr(i, 2);行後面加上i++
  • 既然你想字符輸出,將數據寫入cipherStream時,即cipherStream << (char)value
1

好,你有你的代碼工作的鑄添加到char。只是想我會說明使用流的稍微簡單,更直接的方法,而不繁瑣的指數跟蹤和SUBSTR提取:

std::string convertFromReadable(const std::string& text) 
{ 
    std::istringstream iss(text); 
    std::ostringstream cipherStream; 
    int n; 
    while (iss >> std::hex >> n) 
    { 
     cipherStream << (char)n; 
     // if there's another character it better be ':' 
     char c; 
     if (iss >> c && c != ':') 
      throw std::runtime_error("invalid character in cipher"); 
    } 
    return cipherStream.str(); 
} 

注意最後一個十六進制值之後,如果沒有冒號if (iss >> c...測試將評估false爲將測試,通過回落。

相關問題