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

时间:2016-08-01 22:43:02

标签: java encryption vigenere

我已经投入了大量精力使密码更加健壮,因此输出区分大小写。

意思是,如果大写字母在消息字符串中,则输出将在该位置的字符串中具有编码的大写字母。例如,:_destroy变为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;
}

1 个答案:

答案 0 :(得分:0)

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