【发布时间】:2013-05-07 23:14:03
【问题描述】:
我正在尝试加密,然后解密文件。当我尝试解密文件时,我想在屏幕上显示内容以确保解密过程没有问题。但是,我没有任何文件解密的显示。我不确定我的代码中缺少什么。我正在使用 Dev_C++。您的帮助将不胜感激。代码如下。
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
string line;
string file, encrfile;
int i, key_length, longueur;
unsigned int key=0;
char ch[100];
cout<<"enter a secret key: ";
cin.getline(ch, 100);
for (i=0;ch[i];i++)
key=(key+3)*ch[i];
cout<<"Password generated: "<<key;
cout<<"\n\nEnter the name of the input file: ";
getline(cin,file);
cout<<"\nEnter the name of the output file: ";
getline(cin,encrfile);
ifstream IS;
IS.open(file.c_str() );
ofstream OS;
OS.open(encrfile.c_str());
while(IS>>line);
{
//encrypting each character
for (i=0;i<line.length();i++)
{
line[i]^=rand()>>8;
OS<<line[i]; //writing the character in the output file
}
}
IS.close();
OS.close();
cout<<"File "<<encrfile<<" has been encrypted"<<endl;
cout<<"\nEnter the name of the file to decrypt: ";
getline(cin,encrfile);
cout<<"\n\nDecryption of file: "<<endl;
ifstream IS2;
IS2.open(encrfile.c_str());
while(IS2>>line);
{
for (i=0;i<line.length();i++)
{
line[i]^=rand()>>8;
cout<<line[i];
}
}
IS2.close();
return 0;
}
【问题讨论】:
-
你正在写出随机字节,你期望会发生什么?
-
您不会将密钥用于任何事情。
-
注意:
while(IS>>line)读取的是一个单词而不是一行。因此,您将从文件中删除所有空格。 -
注意:while(IS>>line)**;** 你有一个栏杆
;这意味着 while 循环没有主体。 -
您的“加密”不保留格式。然而,它依赖于能够从 加密 数据中读取行,因为原始 plaintext 由行组成。这从根本上被打破了。
标签: c++ file encryption