简体   繁体   中英

C++ Caesar Cipher encryption

can anyone explain how this set of code works ?

string LoginAccess::decryptPass(string pass) {

int count = 0;

while (count < pass.length()) {

    if (isalpha(pass[count])) {
        //For Caps lock 
        if (pass[count] > 64 && pass[count] < 91) {
            if (pass[count] < 88) {
                pass[count] += 3;
            } else if (pass[count] == 88) {
                pass[count] = 'A';
            } else if (pass[count] == 89) {
                pass[count] = 'B';
            } else
                pass[count] = 'C';
            //For small char
        } else {
            if (pass[count] < 120) {
                pass[count] += 3;
            } else if (pass[count] == 120) {
                pass[count] = 'a';
            } else if (pass[count] == 121) {
                pass[count] = 'b';
            } else
                pass[count] = 'c';
        }
    }
    count++;
  }

return pass;
}

What do the numbers like 64, 91, etc mean? Why only set it a, b, c ? What happens to the rest of the alphabet?

This function loops the string pass , incrementing count to use as an index for the array. The code is decoding a Ceasar cipher, where each letter is shifted down the alphabet a certain number of places, in this case, three.

It compares the current character ( pass[count] ) with ASCII character codes. Each letter and punctuation mark has a number associated with it. You can see a chart of characters on this page . As you can see there, the capital letters ('A' through 'Z') span 65 to 90, and the lowercase ('a' through 'z') 97 to 122.

So the code checks whether the letter falls in upper or lower case. There it will by default move the letter three spaces forward, but if it did that with the last three letters of the alphabet, that would push into the number of punctuation. So special coditions are put in to check for that. If pass[count] is 88, the character 'X', it is manually set to 'A', the number 65. If it were incremented by three it would become 91, the character, '['.

There are some weaknesses in the code, as it only supports letters. If punctuation marks were in the pass string, they would be changed into another random punctuation, for no reason from the user's perspective.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM