如何解决Java中的Vigenere密码算法-解密为纯文本的消息
我目前正在尝试用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:
D i =(M i -K i + 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。