下面是一些简单 XOR 加密的代码。它提示用户输入消息,后跟密钥,然后使用 128 位块中的密钥对消息进行加密。
当输入一个短的输入(例如 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;
}
任何其他评论和批评也很感激!谢谢!