2015-12-21 3 views
0

Я не торопился узнать больше о шифровании и просто шифрах вообще. Я начал работать над консольным приложением, чтобы позволить мне шифровать или расшифровывать шифры типа RSA.C++ Unhandled Exception: std :: bad_alloc

Пока все работает хорошо, за исключением тех случаев, когда я включаю символ «n» в строку, которую я хочу зашифровать. По какой-то причине буква «n» заставляет приложение прерывать. Не имеет значения, является ли это «n» само по себе внутри строки других символов. Это просто не нравится «n».

Я все еще студент, когда дело доходит до кодирования, и это только мое второе приложение в C++.

Ошибка:

Unhandled exception at 0x7743C42D in RSA Cipher.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0020DE98.

Мой текущий код:

#include <iostream> 
#include <sstream> 
#include <algorithm> 
#include <math.h> 

using namespace std; 

int main() 
{ 
    //GLOBAL_VARS 
    string mainInput; 
    string aboutInput; 
    string encrInput; 
    int encrKey[2] = {5, 14}; //Temp Key 

    const int nValues = 26; //How many values within the array 
    string letterArray[nValues] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; //Array of letters 
    string capsArray[nValues] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}; //Array of capital letters 

    //MAIN_MENU 
    while ((mainInput != "Exit") || (mainInput != "exit") || (mainInput != "4")) 
    { 
     cout << "\n---RSA Cipher [Main Menu]---\n\n" 
      << "1: About\n" 
      << "2: Encrypt\n" 
      << "3: Decrypt\n" 
      << "4: Exit\n\n"; 

     cin >> mainInput; 

     //ABOUT_MENU 
     if ((mainInput == "about") || (mainInput == "About") || (mainInput == "1")) 
     { 
      cout << "\n---RSA Cipher [About]---\n\n" 
       << "This applicaton was designed to encrypt or decrypt information using RSA encryption.\n\n" 
       << "1: Back\n\n"; 

      cin >> aboutInput; 
     } 
     else { 
      //ENCRYPT_MENU 
      int encrLength; 
      int encrNum; 
      string encrGet; 
      string encrOutput; 

      if ((mainInput == "Encrypt") || (mainInput == "encrypt") || (mainInput == "2")) 
      { 
       cout << "\n---RSA Cipher [Encrypt]---\n\n" 
        << "Enter a string to encrypt.\n\n"; 

       cin >> encrInput; 

       encrLength = encrInput.length(); //Sets the variable to equal the length of the users input so that both items being compared are signed. 

       int iLength = 0; 
       while (iLength < encrLength) 
       { 
        encrGet = encrInput[iLength]; //Grabs a value of the entered string in order 

        int iIndex = 0; 
        while (iIndex < nValues) 
        { 
         if ((encrGet == letterArray[iIndex]) || (encrGet == capsArray[iIndex])) 
         { 
          encrNum = pow(iIndex + 1, encrKey[0]); //Sets the variable to equal array index + 1 (the alphabet starts at 1 not 0) to the power of the first encrKey value 
          encrNum = encrNum % encrKey[1]; //Sets the variable to equal it'self mod the second encrKey value 

          encrOutput = encrOutput + letterArray[encrNum - 1]; //Adds the letters to the soon to be output -1, as we are now dealing with computer logic. 

         } 

         iIndex++; 
        } 
        iLength++; 
       } 
       cout << "Encrypted: " << encrOutput << endl; 
      } 
     } 
    } 
    //END-MAIN_MENU 
} 
+0

Возможно, не в коде, который вы опубликовали. Если вам нужна помощь в поиске и устранении неисправностей вашего кода, вам действительно нужно опубликовать полный пример, который может быть скомпилирован и запущен «кем угодно». –

+0

Кстати, 'bad_alloc' означает, что ваша система не сможет удовлетворить выделение памяти с помощью' new'. Либо потому, что вы просите о сумасшедших объемах памяти, либо в цикле, навсегда выделяя новую память. –

+0

Существует некоторая связь между 'encrKey [1]' is 14 и '' n'', являющимся 14-й буквой. Это может вызвать доступ за пределами диапазона в 'letterArray [encrNum - 1]'. –

ответ

0

Так что проблема была, как @molbdnilo упоминается ...

The problem occurs when encrNum % encrKey[1] is zero, which will happen whenever encrNum == encrKey[1]. It looks like you have a conflict between zero-based and one-based indexing.

К счастью, когда дело с реальным ключ, а не временный простой, этот конфликт не произойдет, поскольку мы будем иметь дело с 2048 бит или 4096 бит ключами. Однако интересно, что проблема возникает, когда modulo возвращает 0 в качестве остатка.