D
D
DDD2019-03-04 17:52:20
C++ / C#
DDD, 2019-03-04 17:52:20

Why does the Vigenère cipher not work for small letters?

Help with small letters cipher

#include <iostream>
#include <string>
#include<algorithm>
#include<cctype>

using namespace std;


class Vigenere
{
public:
  string key;

  Vigenere(string key)
  {
    for(auto &i:key)
    {
      if(i >= 'A' && i <= 'Z')
        this->key += i;
      else if(i >= 'a' && i <= 'z')
        this->key += i;
    }
  }

  string encrypt(string text)
  {
    string out;
    int j=0;

    for(auto &i:text)
    {
      if(i==' '){
          out+=' ';
          continue;
      };

      if(isupper(i))
       out += (i + key[j] - 2*'A') % 26 + 'A';
        else
      out += (i + key[j] - 2*'A') % 26 + 'a';

      j = (j + 1) % key.length();
    }

    return out;
  }

  string decrypt(string text)
  {
    string out;
    int j=0;
    for(auto &i:text)
    {
      if(i==' '){
          out+=' ';
          continue;
      };

      if(isupper(i))
        out += (i - key[j] + 26) % 26 + 'A';
      else
      out += (i - key[j] + 26) % 26 + 'a';

      j = (j + 1) % key.length();
    }

    return out;
  }
};

using namespace std;

int main()
{
  Vigenere cipher("LEMON");

  string original= "ATTA cka";//Должно вывести -> LXFO pve
//  getline(cin,original);
  string encrypted = cipher.encrypt(original);
  string decrypted = cipher.decrypt(encrypted);

  cout <<"Text : "<< original << endl;
  cout << "Key: " << cipher.key << endl;
  cout << "Cipher: " << encrypted << endl;
  cout << "Decipher: " << decrypted << endl;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sumor, 2019-03-04
@Sumor

if(isupper(i))
       out += (i + key[j] - 2*'A') % 26 + 'A';
        else
      out += (i + key[j] - 2*'A') % 26 + 'a';

In the first case, you have i a capital letter, key[j] is a capital letter, so you subtract two A 's.
In the first case, you have i a small letter, key[j] is a capital letter, and you keep subtracting two A's It 's
more correct to group it a little so that it's clear why you are subtracting: And then it will immediately become clear that in the case of a small letter you need: NB: i is a bad name for a variable of type char. When a programmer sees i he means a cyclic numeric variable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question