区分大小写的 Vigenere 密码产生错误的输出

Case sensitive Vigenere cipher produces wrong output

我付出了很多努力来使密码更可靠,以便输出区分大小写。

意思是,如果消息字符串中有大写字母,输出的字符串中该位置将有一个编码的大写字母。例如 InpUT MesSagE 变成 HrhTS WwlReyD。使用的密钥是 test.

public String encrypt(String text, final String key) {
    int a_num = (int) 'a';
    int A_num = (int) 'A';
    String output = "";
    for (int i = 0, j = 0; i < text.length(); i++) {
        int cur = (int) text.charAt(i);
        // check for spaces
        if (text.charAt(i) == ' ') {
            output += " ";
        // check for lowercase
        } else if (cur >= 'a' && cur < 'z' + 26) {
            output += Character.toString((char) ((cur + key.charAt(j) - 2 * 'a') % 26 + 'a'));
            j = ++j % key.length();
        // check for uppercase between 'N' and 'Z'
        } else if (cur >= 'N' && cur < 'Z') {
            output += Character.toString((char) ((cur + key.charAt(j) - 2 * 'A') % 26 + 'N' + 7));
            j = ++j % key.length();
        // check for uppercase between 'A' and 'M'
        } else {
            output += Character.toString((char) ((cur + key.charAt(j) - 2 * 'A') % 26 + 'A' - 6));
            j = ++j % key.length();
        }
    }
    return output;
}

目前,所有小写字母似乎都能正确显示,有些大写字母也能正确显示。我的问题是有时大写是错误的,例如符号将成为输出的一部分,因为我不正确 math/logic.

我非常确定问题出在代码的这些部分中的变量:

((cur + key.charAt(j) - 2 * 'A') % 26 + 'A' - 6));
public String encrypt(String text, final String key) {
    // we assume the key is all lower case
    // and only inputs are letters and space (could enhance to leave all else alone)
    int a_num = (int) 'a'; //unused?
    int A_num = (int) 'A';//unused?
    String output = "";

    for (int i = 0, j = 0; i < text.length(); i++) {
        int cur = (int) text.charAt(i);

        // check for spaces
        if (text.charAt(i) == ' ') {
            output += " ";
        }
        // check for lowercase
        else if (cur >= 'a' && cur <= 'z') {
            output += Character.toString((char) ((cur + key.charAt(j) - 2 * 'a') % 26 + 'a'));
            j = ++j % key.length();
        }
        // should work for uppercase between 'A' and 'Z'
        else {
            output += Character.toString((char) ((cur -'A' + key.charAt(j) - 'a') % 26 + 'A'));
            j = ++j % key.length();
        }
    }
    return output;
}