шифрование с использованием C ++ (ошибки чтения зашифрованного текста) - PullRequest
0 голосов
/ 20 мая 2011

это первый раз, когда я использую этот форум, и я сделал это из чистого отчаяния.Я должен написать программу шифрования, которая использует алгоритм Des.Мне удалось отлично написать код Des, и он работает без ошибок из памяти.Но моя проблема начинается, когда я должен прочитать зашифрованный текст из файла, а затем расшифровать его.Иногда это работает, а другие нет.Я пробовал так много способов обойти проблему, но не достиг нигдеВот основной код без самого кода Des.Пожалуйста, помогите мне

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

1 Ответ

0 голосов
/ 20 мая 2011

Возможно, это не ваша проблема, но в вашей программе есть как минимум два неопределенных поведения.Вы записываете один байт сверх выделения для 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;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...