C++ 尝试读取文本文件,用XOR加密,然后将其写入新的文本文件

C++ 尝试读取文本文件,用XOR加密,然后将其写入新的文本文件,c++,encryption,bit-manipulation,xor,C++,Encryption,Bit Manipulation,Xor,我正在尝试设计一个程序,可以打开任何文本文件,将其读入字符串,用XOR加密字符串,然后将字符串写入新的文本文件。下面的代码可以工作,但会生成多个“系统蜂鸣音” 我的猜测是我没有正确处理空格?我不确定。知道我做错了什么吗 #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream inFile; ofstr

我正在尝试设计一个程序,可以打开任何文本文件,将其读入字符串,用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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
河流充填;
出流孔的直径;
//定义变量
字符串文件名,
key=“seacrest out”;
//输入
cout>文件名;

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

如果你拆下这条线

cout << str << endl;

cout当你用一些随机键对字节进行异或运算时,你会得到一些不寻常的字节序列。这些字节序列恰好与一些不可打印的字符相对应,你可以通过将它们发送到控制台来让控制台发出嘟嘟声

如果你拆下这条线

cout << str << endl;

cout您听到的那些嘟嘟声的字节数等于文件中的0x07。您只需不在控制台中打印二进制文件的内容即可解决此问题。

您听到的那些嘟嘟声的字节数等于文件中的0x07。您只需不在控制台中打印二进制文件的内容即可解决此问题ole。

为自己尝试这么做而感到荣幸。 问题是您没有仔细处理某些字符,例如,可能会打印出空白字符

chard=(char)(7)

printf(“%c\n”,d)

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


你自己尝试做这件事真是太好了。 问题是您没有仔细处理某些字符,例如,可能会打印出空白字符

chard=(char)(7)

printf(“%c\n”,d)

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


为了避免此问题,您可以对xor值进行编码,例如将十六进制值写入字符串0x07->“07”为了避免此问题,您可以对xor值进行编码,例如将十六进制值写入字符串0x07->“07”