使用C++进行加密(错误读取密文)

问题描述:

这是我第一次使用这个论坛,而且我是用纯粹的绝望来做到这一点的。我应该写一个利用Des algorythm的加密程序。我设法很好地编写了Des代码,并且它在内存中没有任何错误。但是当我必须从文件中读取密文并解密时,我的麻烦才开始。它有时有效,而其他则不行。我尝试了很多方法来解决这个问题,但没有达到目的。这里是没有Des代码本身的主代码。请帮助我使用C++进行加密(错误读取密文)

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; 
} 
+2

定义 “不工作”。它会崩溃吗?它是否提供错误信息?它会产生错误的结果吗?你有没有尝试用调试器来浏览你的程序,看看它出错了? – 2011-05-20 15:36:14

+0

只是一个预感,因为你没有提供有关这个问题的信息,你的文件可能有控制字符,如回车,换行等,你没有遇到你的内存测试。 – AJG85 2011-05-20 15:40:18

+2

你为什么用'new'分配东西? – 2011-05-20 15:40:25

这可能不是您的问题,但您的程序中至少有两个未定义的行为。你写一个字节超出分配strres

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; 
+0

感谢您的帮助,但这对输出没有任何影响。我仍然得到垃圾的字符。 – 2011-05-20 16:25:39