在不知道密钥但知道明文将包含的字之一的情况下解密移位密码的方法-java

vktxenjb  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(309)

我目前正在尝试编写一个应用程序,它应该从一个文件中读取密文,并使用移位密码解密它,而不知道密钥,但知道字符串中的一个单词是“done”。这是我到目前为止使用的方法,它遍历所有25个键,我试图检查string.contains(“done”)是否存在,但不管出于什么原因,它都好像该方法甚至不承认特定if语句的存在,只遍历所有25个键。我知道答案可能很明显,但我就是看不出来。。。这是我的密码:

public String decryptUnknownKey()
    {
        char[] ciphertext = this.ciphertext.toUpperCase().toCharArray();
        char c;
        char[] plaintext = new char[ciphertext.length];
        String test = "";
        String search = "DONE";
        boolean keyFound = false;

        while(!keyFound)
        {
            for (int key = 1; key < 25; key++)
            {
                for (int i = 0; i < ciphertext.length; i++)
                {
                    if(ciphertext[i] >= 'A' && ciphertext[i] <= 'Z')
                    {
                        c = (char) (Math.floorMod(ciphertext[i] - 65 - key, 26) + 65);
                        plaintext[i] = c;
                    }
                    else if(Character.isWhitespace(ciphertext[i]) == true)
                    {
                        plaintext[i] = 32;
                    }
                }
                test = String.valueOf(plaintext);
                if (test.contains(search))
                {
                    keyFound = true;
                }
            }
        }
        return test;
    }
hgb9j2n6

hgb9j2n61#

您正在嵌套三个循环

a) while
b) -- for
c)    -- for

外部for循环b)在所有键上保持循环,即使它设置keyfound=true。这是因为您使用keyfound作为a)的退出条件,而不是b)的退出条件。因此b)将继续,直到它尝试了所有键,然后a)重新评估。注意,如果没有合适的键,while循环将永远不会终止。
嵌套循环通常被认为是一种代码味道。您可能只想完全移除外部while循环,第一步只使用b)和c)。要终止外部for循环,请使用break语句而不是布尔标志。这是一些样品https://www.tutorialspoint.com/java/java_break_statement.htm

相关问题