#include "cryptclasscaesar.h" const int CryptClassCaesar::LOWERBOUND = 'A'; const int CryptClassCaesar::UPPERBOUND = 'Z'; /** * @brief CryptClassCaesar::CryptClassCaesar constructor for caesar encryption */ CryptClassCaesar::CryptClassCaesar() :CryptClassBase() { qDebug("CryptClassCaesar::CryptClassCaesar()"); } /** * @brief CryptClassCaesar::~CryptClassCaesar destructor for caesar encryption */ CryptClassCaesar::~CryptClassCaesar() { qDebug("CryptClassCaesar::~CryptClassCaesar()"); } /** * @brief CryptClassCaesar::encrypt encrypt the PlainText with the specific rotation */ void CryptClassCaesar::encrypt() { qDebug() << "CryptClassCaesar::encrypt()"; buildMap(); // convert into upper letters m_clearText = m_clearText.toUpper(); // clear cryptText m_cryptText.clear(); // Set offset into 0 mapOffset = 0; // Space counter int spaceCount = 0; for (int i = 0; i < m_clearText.size(); i++) { // only accept letters between 'A' and 'Z' if (m_clearText[i] >= (char) LOWERBOUND && m_clearText[i] <= (char) UPPERBOUND) { // encrypt Letters and rotate roter m_cryptText.append(substitutionsMap[LOWERBOUND + (((m_clearText[i] - LOWERBOUND) + mapOffset++) % (26))]); // insert spaces if (!(++spaceCount % 5)) { m_cryptText.append(" "); } } } } /** * @brief CryptClassCaesar::decrypt encrypt the PlainText with the specific rotation */ void CryptClassCaesar::decrypt() { qDebug("CryptClassCaesar::decrypt()"); buildMap(); int tmp = 0; m_cryptText = m_cryptText.toUpper(); // delete clear text m_clearText.clear(); // set offset into 0 mapOffset = 0; for (int i = 0; i < m_cryptText.size(); i++) { // only accept letters between 'A' and 'Z' if (m_cryptText[i] >= (char) LOWERBOUND && m_cryptText[i] <= (char) UPPERBOUND) { // decrypt letters and rotate rotor backwards tmp = ((substitutionsMap.key(m_cryptText[i]) - LOWERBOUND) - mapOffset++) % (26); // to hack the modulo operator if (tmp < 0) { //Because tmp is negative adding it to UPPERBOUND subtracts it //Also plus 1 because -1 is the highest negative number m_clearText.append(UPPERBOUND + tmp + 1); } else { m_clearText.append(LOWERBOUND + tmp); } } } } /** * @brief CryptClassCaesar::buildMap fill the map with information */ void CryptClassCaesar::buildMap() { bool ok = false; int rotor = getKey().toInt(&ok); if (ok == false || rotor < 1 || rotor > 5) { QMessageBox::warning(NULL, "Key invalid", "The key for Enigma should only be a number between 1 and 5."); return; } rotor--; // Char Array to simple implement the rotor char rotors[5][27] = { "EKMFLGDQVZNTOWYHXUSPAIBRCJ", "AJDKSIRUXBLHWTMCQGZNPYFVOE", "BDFHJLCPRTXVZNYEIWGAKMUSQO", "ESOVPZJAYQUIRHXLNFTGKDCMWB", "VZBRGITYUPSDNHLXAWMJQOFECK" }; // Clear substitution Map substitutionsMap.clear(); for (int i = 0; i <= (UPPERBOUND - LOWERBOUND); i++) { substitutionsMap.insert((char)(LOWERBOUND + i), rotors[rotor][i]); } }