【发布时间】:2020-10-03 21:53:56
【问题描述】:
我目前正在尝试用 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));
}
}
【问题讨论】:
-
在你的“解密代码”中,
msg[i]不应该以某种方式参与吗? -
@KevinAnderson 我确实在解密代码部分添加了它,msg[i] + key[i] + 26...但它仍然没有用,所以我把它拿出来了。抱歉应该评论出来
-
我想你可能想要更像
((msg[i] - 'A') + (key[i] - 'A')) % 26 + 'A'的东西。或者((msg[i] - 'A') - (key[i] - 'A')) % 26 + 'A',这取决于文本最初的加密方式。