Search code examples
javacaesar-cipher

Need explanation for code in Caesar cipher


Hey so recently I got tasked with creating an app that reads a message and ecrypts it with the Caesar cipher in Java.

I didn't really have a problem until I came to the part where adding the numberic cipher would take you over letters a-z/A-Z into special symbols and I did not really know what to do.

Here is the code of my solution:

private String caesarCipher(String message) {
    Scanner input = new Scanner(System.in);
    StringBuilder cipher = new StringBuilder();
    char ch;
    int key;

    System.out.print("Enter a key: ");
    key = Integer.parseInt(input.nextLine());

    for(int i = 0; i < message.length(); i++) {
        ch = message.charAt(i);
        if(ch >= 'a' && ch <= 'z'){
            ch = (char)(ch + key);

            if(ch > 'z'){
                ch = (char)(ch - 'z' + 'a' - 1);
            }

            cipher.append(ch);
        }
        else if(ch >= 'A' && ch <= 'Z'){
            ch = (char)(ch + key);

            if(ch > 'Z'){
                ch = (char)(ch - 'Z' + 'A' - 1);
            }

            cipher.append(ch);
        }
        else {
            cipher.append(ch);
        }
    }

    return cipher.toString();
}

Could someone please explain to me the process and reasoning behind the following statement:

if(ch > 'z'){
    ch = (char)(ch - 'z' + 'a' - 1);
}

Solution

  • It will never allow an encrypted character to exceed its supposed range, that is, a - z. The ascii of a and z are 97 and 122 respectively, and you would want the Caesar cipher encryption within this range of characters only.

    This will check if the ascii code of ch is greater than the ascii of z

    if(ch > 'z'){
    

    If yes, it will calculate: (ascii of ch) - (ascii of z) + (ascii of a) - 1.

    ch = (char)(ch - 'z' + 'a' - 1);
    

    It is translated into ch = (char)(ch - 122 + 97 - 1);

    Suppose you want to encrypt character a with a key 3. The program will take 97 (ascii of a) + 3. You will get 100, which is the ascii of d. Yet, what if you want to encrypt z with a key 3?

    Same as before, it will take 122 (ascii of z) + 3 = 125. However, 125 is not found in the range 97 - 122 (a-z). Thus, you will get an unwanted character (in this case, 125 is the ascii of }).

    Therefore, (ch - 'z' + 'a' - 1) will ensure that any character exceeding ascii 122, will be converted back into a character with ascii range of 97 and 122 inclusive only. In the example of 125, ch = (char)(125 - 122 + 97 - 1) => ch = (char)(99) => ch = c.