简体   繁体   中英

Case sensitive Vigenere cipher produces wrong output

I have put a lot of effort into making a cipher more robust so that the output is case sensitive.

Meaning, if a capital letter is in the message string, the output will have an encoded capital letter in the string at that location.. For example InpUT MesSagE turns into HrhTS WwlReyD . The key used is 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;
}

Currently, all lowercase letters seem to come out right, and some of the uppercase do. My problem is sometimes the uppercase is wrong, for instance symbols will be part of the output because of my incorrect math/logic.

The variables that I'm pretty sure are the issue are in these sections of the code:

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

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