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;
- The first subtraction should shift the number range
- Then we will subtract the key as how the Caesar decryption is defined
- We add 26 to deal with negative numbers (?)
- The module will limit the output as the range of the ASCII numbers is 26 length
- 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] - 65brings the ASCII rangeA..Zinto an integer range 0..25(cipher[i] - 65 26 - key) % 26rotates that value left bykey(subtractskeymodulo 26)65to shift the range 0..25 back into ASCII rangeA..Z.
e.g. given a key of 2, A becomes Y, B becomes Z, C becomes A, etc.
