Java 中的 Vigenere 密码算法 - 将消息解密为明文

Vigenere Cipher Algorithm In Java - Decrypted Message to Plaintext

我目前正在尝试在 Java 中编写 Vigenere Cipher 算法。我必须将解密的消息更改为明文但遇到问题。以下是我目前所拥有的。

当我 运行 它时,消息没有被正确破译。

import java.util.Scanner;

public class VigenereCipher {
        public static void main(String arg[]) {
            String message = "";
            String keyword = "KISWAHILI";
            
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter a message: ");
            message = sc.nextLine();
            
            char msg[] = message.toCharArray();
            int msgLength = msg.length;
        
            
            char key[] = new char [msgLength];
            char decryptedText[] = new char[msgLength];
            
            for(int i = 0, j = 0; i < msgLength; i++, j++) {
                if(j == keyword.length()) {
                    j = 0;
                }
                key[i] = keyword.charAt(j);
            }
            
            // Decryption Code
            for(int i =0; i < msgLength; i++) {
                decryptedText[i] = (char)(((key[i] + 26) % 26) + 'A');
            }
            System.out.println("Decrypted Message: " + message);
            System.out.println("Keyword: " + keyword);
            System.out.println("Plaintext: " + String.valueOf(decryptedText));
        }
}

似乎在填充 key 数组时需要跳过空格:

for (int i = 0, j = 0; i < msgLength; i++) {
    if (msg[i] == ' ') {
        key[i] = ' ';
    } else {
        key[i] = keyword.charAt(j++ % keyword.length());
    }
}
System.out.println("Key Message:       " + new String(key));

同样,在解密循环中也需要考虑到。 并解密has to be fixed
Di = (Mi - Ki + 26 ) mod 26

for (int i =0; i < msgLength; i++) {
    char c = msg[i];
            
    decryptedText[i] = c == ' ' ? c : (char)(((msg[i] - key[i] + 26) % 26) + 'A');
}

应用这些更改后,输出如下:

Key Message:       KISW AH ILIKI SW AHILIKIS WAH ILI KISW AHILIKISW AHIL IKIS
Encrypted Message: XQKP IZ IMWEB LK AUVZCXKW PHL VPE RIKD ASOZZSBZI TOIE ESTD
Keyword: KISWAHILI
Plaintext: NIST IS ABOUT TO ANNOUNCE THE NEW HASH ALGORITHM THAT WILL