需要对凯撒密码中的代码进行解释

问题描述 投票:-1回答:1

嘿,最近我受命创建一个应用程序,该应用程序读取消息并使用Java中的Caesar密码对其进行加密。

我真正地没有问题,直到我进入将数字密码添加到特殊符号中将字母a-z / A-Z带到您的那部分,而我真的不知道该怎么做。

这是我的解决方案的代码:

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();
}

有人可以向我解释以下陈述的过程和推理:

if(ch > 'z'){
    ch = (char)(ch - 'z' + 'a' - 1);
}
java caesar-cipher
1个回答
0
投票

它绝不会允许加密字符超出其假定范围,即a-z。 a和z的ascii分别为97和122,并且您只希望在此字符范围内进行Caesar密码加密。

这将检查ch的ASCII码是否大于z的ASCII码

if(ch > 'z'){

如果是,它将计算:(ch的ascii)-(z的ascii)+(a的ascii)-1。

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

它翻译为ch = (char)(ch - 122 + 97 - 1);

假设您想用密钥a加密字符3。该程序将花费97(a的ascii)+3。您将获得100,即d的ascii。但是,如果要用密钥z加密3,该怎么办?

与之前相同,将需要122(z的ascii)+ 3 =125。但是,在97-122(a-z)的范围内找不到125。因此,您将得到一个不需要的字符(在这种情况下,}的ascii为125)。

因此,(ch - 'z' + 'a' - 1)将确保任何超过ascii 122的字符都将转换回ascii范围仅在97和122(含)之间的字符。在125的示例中,ch = (char)(125 - 122 + 97 - 1) =>ch = (char)(99)=> ch = c

© www.soinside.com 2019 - 2024. All rights reserved.