0

I can not seem to figure out why only certain letters in my decryption are not working. I am trying to decrypt the letters kddkmu with a key of 10. It is suppose to come out to attack but every time I run the code it comes out to aZZack. I believe the problem has something to do with my modulus operation but no matter what I do I cant figure out the problem.

int key = 10;
ciphertext = "kddkmu";
plaintext = shift_decrypt(ciphertext, key);

cout << "2. Decryption of the ciphertext: " << ciphertext << endl;

cout << "   Key: " << key << endl;

cout << "   Plaintext; " << plaintext << endl << endl;

with

string shift_decrypt(string p, int a)
{
    string dtext = "";

    for (int i = 0; i < p.length(); i++)
    {
        dtext += char(int(p[i] - a - 97) % 26 + 97);
    }

    return dtext;
}

I am not getting any errors its just decrypting the dd as ZZ for some odd reason

Water
  • 3,245
  • 3
  • 28
  • 58
namlay557
  • 25
  • 1
  • 5
  • 1
    in c++, modulus of a negative will be negative – kmdreko Oct 01 '19 at 19:49
  • I've already provided the hints and links in your previous [question](https://stackoverflow.com/a/58189369/1820553). – kelalaka Oct 01 '19 at 19:55
  • Break down the math and inspect step by step. Step 1: Have lots of fun. Step 2 `int shifted = ch - a -97;` Print it out and make sure it is correct Step 3: `int modded = shifted % 26;` Again, print and check. Step 4: `int shifted_back = modded + 97;` Print and check. Then make sure the message encrypted correctly. – user4581301 Oct 01 '19 at 20:01
  • 2
    What's significant about 97? Do you mean `'a'`? If so, then use `'a`' instead. – Thomas Matthews Oct 01 '19 at 20:24

1 Answers1

0

I don't suggest subtraction with modulus (remainder) operator.

We know that (X * 26) % 26 == 0 for all X.
So, we can add an extra 26 with no cost. To subtract, we can add (26 - Y) to the value and still have a positive value.

Step by step:
1) Shift the character into the range of 0 - 25, inclusive:
int value = letter - 'a';

2) Remove the Caesar offset by "subtracting" the key:
value = (value + 26 - key) % 26;

3) Shift the value to the range a to z:
char decrypted_letter = value + 'a';

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154