Home > Mobile >  Trouble understanding Caesar decryption steps
Trouble understanding Caesar decryption steps

Time:01-18

The following code will decrypt a caesar encrypted string given the ciphertext and the key:

#include <iostream>

std::string decrypt(std::string cipher, int key) {
    std::string d = "";
    for(int i=0; i<cypher.length();i  ) {
        d  = ((cipher[i]-65-key 26) &) 65;
    }
    return d;
}

int main()
{
    std::cout << decrypt("WKLVLVJRRG", 3) << std::endl; // THISISGOOD
    std::cout << decrypt("NBCMCMAIIX", 20) << std::endl; // THISISGOOD
}

I'm having trouble to understand the operations performed to compute the new character ASCII code at this line:

d  = ((cipher[i]-65-key 26) &) 65;
  1. The first subtraction should shift the number range
  2. Then we will subtract the key as how the Caesar decryption is defined
  3. We add 26 to deal with negative numbers (?)
  4. The module will limit the output as the range of the ASCII numbers is 26 length
  5. We come back to the old range by adding 65 at the end

What am I missing?

CodePudding user response:

If we reorder the expression slightly, like this:

d  = (((cipher[i] - 65)   (26 - key)) % 26)   65;

We get a formula for rotating cipher[i] left by key:

  • cipher[i] - 65 brings the ASCII range A..Z into an integer range 0..25
  • (cipher[i] - 65 26 - key) % 26 rotates that value left by key (subtracts key modulo 26)
  • 65 to shift the range 0..25 back into ASCII range A..Z.

e.g. given a key of 2, A becomes Y, B becomes Z, C becomes A, etc.

  •  Tags:  
  • Related