这是我第一次使用这个论坛而且是出于纯粹的绝望而做到的。我应该写一个利用Des algorythm的加密程序。我设法完美地编写了Des代码并且它在没有任何内存错误的情况下工作。但是当我必须从文件中读取密文然后解密它时,我的麻烦就开始了。它有时有效,有些则无效。我尝试了很多方法来解决这个问题,但没有达到目的。这是没有Des代码本身的main代码。请帮帮我
int main()
{
Des d1,d2;
char *str=new char[1000];
char *str1=new char[1000];
char c;
ifstream *keyFile;
ofstream cipherFile ;
keyFile= new ifstream;
keyFile->open ( "key.txt", ifstream::binary) ;
binaryToHexa (keyFile);
cipherFile.open ( "ciphertext.dat", ofstream::binary) ;
std::ifstream plainFile("plaintext.txt", ifstream::binary);
plainFile.seekg(0, std::ios::end);
std::ifstream::pos_type filesize = plainFile.tellg();
plainFile.seekg(0, std::ios::beg);
std::vector<char> bytes(filesize);
plainFile.read(&bytes[0], filesize);
str = new char[bytes.size() + 1]; // +1 for the final 0
str[bytes.size() + 1] = '\0'; // terminate the string
for (size_t i = 0; i < bytes.size(); ++i)
{
str[i] = bytes[i];
}
char *temp=new char[9];
for(int i=0; i<filesize; i+=8)
{
for(int j=0; j<8; j++)
{
temp[j]=str[i+j];
}
temp[8]='\0';
str1=d1.Encrypt(temp);
cipherFile<<str1;
//cout<<d2.Decrypt(str1);
}
cipherFile.close();
plainFile.close();
std::ifstream cipherFileInput("ciphertext.dat", std::ios::binary);
cipherFileInput.seekg(0, std::ios::end);
std::ifstream::pos_type filesize2 = cipherFileInput.tellg();
cipherFileInput.seekg(0, std::ios::beg);
std::vector<char> bytes2(filesize2);
char* res;
cipherFileInput.read(&bytes2[0], filesize2);
res = new char[bytes2.size() + 1]; // +1 for the final 0
res[bytes2.size() + 1] = '\0'; // terminate the string
for (size_t i = 0; i < bytes2.size(); ++i)
{
res[i] = bytes2[i];
}
char *temp2=new char[9];
for(int i=0; i<filesize2; i+=8)
{
for(int j=0; j<8; j++)
{
temp2[j]=res[i+j];
}
temp2[8]='\0';
str1=d2.Decrypt(temp2);
cout<<str1;
}
return 1;
}
答案 0 :(得分:0)
这可能不是您的问题,但您的程序中至少有两个未定义的行为。您在str
和res
的分配之外写了一个字节:
str = new char[bytes.size() + 1]; // +1 for the final 0
str[bytes.size() + 1] = '\0'; // terminate the string
...
res = new char[bytes2.size() + 1]; // +1 for the final 0
res[bytes2.size() + 1] = '\0'; // terminate the string
这些作业应该是:
str[bytes.size()] = 0;
和
res[bytes2.size()] = 0;