0

我正在尝试设计一个程序,它将打开任何文本文件,将其读入字符串,用 XOR 加密字符串,并将字符串写入新的文本文件。下面的代码有效,但会产生多个“系统哔声”。

我的疯狂猜测是我没有正确处理空格?我不确定。任何想法我做错了什么?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ifstream inFile;
    ofstream outFile;

    // Define variables
    string fileName,
        key = "seacrest out";

    // Input
    cout << "Please enter the name of the file you wish to encrypt: ";
    cin >> fileName;
    cout << endl;

    inFile.open(fileName, ios::in | ios::binary);
    string str((istreambuf_iterator<char>(inFile)), istreambuf_iterator<char>()); // Reads a text file into a single string.
    inFile.close();
    cout << "The file has been read into memory as follows:" << endl;   
    cout << str << endl;
    system("pause");

    // Encryption
    cout << "The file has been encrypted as follows:" << endl;
    for (unsigned x = 0; x < str.size(); x++)           // Steps through the characters of the string.
        str[x] ^= key[x % key.size()];                  // Cycles through a multi-character encryption key, and encrypts the character using an XOR bitwise encryption.
    cout << str << endl;                                // This code works, but I get system beeps. Something is still wrong.

    // Write Encrypted File
    cout << "Please enter the file name to save the encrypted file under: ";
    cin >> fileName;
    cout << endl;

    outFile.open(fileName, ios::out | ios::binary);
    outFile.write(str.c_str(), str.size());         // Writes the string to the binary file by first converting it to a C-String using the .c_str member function.

    system("pause");

return 0;
}
4

3 回答 3

2

尝试自己做的荣誉。问题是您没有仔细处理某些字符,例如空格可能会尝试打印出来

字符 d=(字符)(7);

printf("%c\n",d);

这被称为钟字符。这是 XOR 加密的简单实现,但我建议编写您自己的版本

http://programmingconsole.blogspot.in/2013/10/xor-encryption-for-alphabets.html

于 2013-11-29T13:58:04.850 回答
2

您听到的那些哔声是文件中等于 0x07 的字节。您可以通过不在控制台中打印二进制文件的内容来摆脱这个问题。

于 2012-05-28T07:18:47.603 回答
1

当你用一些随机键异或字节时,你会得到一些不寻常的字节序列。这些字节序列恰好对应于一些不可打印的字符,您可以通过将它们发送到控制台来使控制台发出哔哔声。

如果您删除该行

cout << str << endl;

您会发现您的控制台不再发出哔哔声,因为您没有打印控制台解释为哔哔声命令的错误字节序列。

如果您的控制台设置为 ASCII 模式(我认为这是因为您有system("PAUSE")这表明您在 Windows 上,除非您明确设置它 IIRC,否则控制台不是 Unicode),那么那些不可打印的字符都是小于 0x1F 的字节和字节0x7F,导致控制台发出蜂鸣声的字符是 0x7(称为“bell”)。

tl;博士

您在加密数据中得到一些 0x7 字节,导致控制台在打印时发出哔哔声。删除cout << str << endl;以修复它。

于 2012-05-28T07:15:06.350 回答