C++ ofstream输出文件不等于输出到文件

C++ ofstream output file does not equal output to file

我正在使用一种简单的算法来加密文本文档。它对前 120 个字符工作正常。我的问题是控制台输出和输出文件中写入的加密内容之间的区别。 你能帮帮我吗?

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <fstream>
#include <string>
#include <stdio.h>
using namespace std;

int main() {
int Ra;
string filename;
cout<< "enter file name to encrypt"<<endl;
getline(cin,filename);
filename.append(".txt");
string line;
string page;
 ifstream infile;
infile.open (filename.c_str());
if (infile.is_open())
{
 while ( getline (infile,line) )
 {
   cout << endl<<line << '\n';
 page=page+line;
}
infile.close();
}
else
{cout << "Unable to open file";
exit(1);}
char page2[page.length()];
//convert string to char
for (int a=0;a<=page.length()-1;a++)
    {
        page2[a]=page[a];

    }
char output[page.length()];

srand (time(NULL));
int seed=rand() % 99900000;

srand (seed);
//encrypt
for(int b=0;b<=page.length()-1;b++){
Ra=rand() % 1000;
output[b]=page2[b]+Ra;
cout<<b<<","<<page[b]<<","<<page2[b]<<","<<output[b]<<endl;
}

//display+put back
cout<<"output encrypted"<<endl;
ofstream outfile ;
outfile.open (filename.c_str(),ios::trunc);
if (outfile.is_open()){
    cin.sync();
for (int c=0;c<=page.length()-1;c++){
cout<<output[c]<<", ";
outfile<<output[c];
    }
 outfile.close();
}
else cout << "Unable to open file";
cout<<endl<<"key= "<<seed;
cout << endl << "Press any key to continue...";
cin.sync();
cin.ignore();
return 0;
}

original text doc

output and final result not equal

char page2[page.length()]; //?
//convert string to char
for (int a=0;a<=page.length()-1;a++) page2[a]=page[a];
char output[page.length()];

您不需要使用它来将字符串转换为字符数组。 page 已经将字符保存在数组中。如果您愿意,可以使用 std::string page2 = page;std::string output = page;

Ra=rand() % 1000;
output[b]=page2[b]+Ra;

每个字节包含一个介于 0 到 255 之间的值。如果您添加一个不超过 1000 的随机值,那么您将无法撤消操作。

在此 ghetto 加密方案中,您不想超过 char 限制。您可以改用 ^ 运算符。然后将加密后的数据写入二进制格式:

srand(seed);
string output = page;
for(size_t b = 0; b < page.length(); b++)
    output[b] ^= (rand() % 0xFF);

ofstream outfile("encrypted.binary", ios::binary);
outfile.write(output.data(), output.size());
outfile.close();

然后您可以再次读取数据(以二进制形式)并再次使用 XOR 运算符:

std::string decrypt = output;
srand(seed);
for(size_t b = 0; b < page.length(); b++)
    decrypt[b] ^= (rand() % 0xFF);

ofstream filedecrypt("decrypted.txt");
filedecrypt.write(decrypt.data(), decrypt.size());
filedecrypt.close();

编辑:

请注意,这 "obfuscation" 不是加密。它还要求程序由同一 compiler/machine 制作,以便可以复制 rand 中的重复。

真正的加密你可以研究一下AES。在最简单的解释中,AES 使用密钥。这个密钥有点像密码,但它最多 32 个字节长,它不是从 A 到 Z,而是从 0 到 255。

AES 使用他们的密钥,加上安全的随机数生成器,来创建一个长度为 16 字节的加密块,假设这些随机字节:

{29, 23, BE, 84, E1, 6C, D6, AE, 52, 90, 49, F1, F1, BB, E9, EB}

然后将其与明文进行异或以创建密文。然后AES会根据前一个块、前16个字节的明文和秘钥制作另一个16字节的加密块。

以最简单的方式,这与您正在做的有点相似,但它不是从 rand() 获取一个字节,而是从 aes() 获取 16 个字节。来自 AES 的序列不能断言(除了需要一百万年的暴力攻击)

使用像 OpenSSL 这样的库来实现 AES 加密。