2012-11-09 37 views
0

下面是簡單異或加密的一些代碼。它會提示用戶輸入消息,然後輸入密鑰,然後使用128位塊中的密鑰加密消息。當一串長字符傳遞給第一個字符時,爲什麼第二個cin的輸入暫停?

當輸入一個短輸入(例如:test)作爲消息(第一個cin調用)時,程序會暫停並等待來自該鍵的輸入。

如果我輸入一個更長,更豐富的文本信息(例如:Now is the winter of our discontent),程序立即從cin調用返回,無法輸入。任何想法爲什麼發生這種情況

#include <iostream> 
#include <iomanip> 
#include "string.h" 
#include "assert.h" 

using std::cout; 
using std::cin; 
using std::endl; 
using std::string; 

string getMessage(); 
string getPassphrase(); 
string setKey(string key); 
string xorECB(string msg, string key); 
char knownPlaintext(char ciphertext, char plaintext); 

struct cipherblock 
{ 
    char block[16]; 
}; 

int main(void) 
{ 
    string plaintext = getMessage(); 
    string key = getPassphrase(); 

    string ciphertext = xorECB(plaintext, key); 

    cout << plaintext.size() << endl; 
    cout << key.size() << endl; 
    cout << ciphertext.size() << endl; 

    return 0; 
} 

string getMessage() 
{ 
    cout << "Message: "; 

    string msg; 
    cin >> msg; 
    cin.ignore(); 

    return msg; 
} 

string getPassphrase() 
{ 
    cout << "Key: "; 

    string key; 
    cin >> key; 
    cin.ignore(); 

    return setKey(key); 
} 

string setKey(string key) 
/// Create 128-bit key from arbitrary-length ASCII passphrase. 
{ 
    if (key.size() == 16) 
     return key; 

    if (key.size() < 16) 
     key += key.substr(0, 16 - key.size()); 
    else 
    { 
     string keyxor = key.substr(16, key.size()); 
     key.erase(16, key.size() - 16); 

     for (int i; i < keyxor.size(); i++) 
      key[i] ^= keyxor[i]; 
    } 

    return setKey(key); // keys shorter than 8 bytes need to be built recursively 
} 

string xorECB(string msg, string key) 
/// XOR cipher operating in ECB mode, 128-bit block size 
{ 
    assert(key.size() == 16); // 16 bytes = 128 bits 
    //for(int i = 0; i < msg.size(); i++) 
     //msg[i] ^= key; 

    for (int i = 0; i < msg.size()/sizeof(cipherblock); i++) 
    { 
     cipherblock *block = (cipherblock*)msg[0]; 

     for (int idx = 0; idx < key.size(); idx++) 
      block->block[idx] ^= (char)key[idx]; 

     block++; 
    } 

    return msg; 
} 

char knownPlaintext(char ciphertext, char plaintext) 
{ 
    return ciphertext^plaintext; 
} 

任何其他意見和批評也感激!謝謝!

回答

3

輸入運算符>>以空格(即單詞之間的空格)停止。如果你想得到一整行,你應該使用例如std::getline

+0

謝謝!我是否還需要'cin.ignore'調用來刷新輸入緩衝區中的'\ n'? – blz

+0

@blz不需要,「分隔字符」(通常換行符)從流中提取,但在使用'std :: getline'時不會被存儲。 –

0

cin會在第一個空白出現後停止輸入。所以,你只會得到一個單詞作爲輸入。

相關問題