【发布时间】:2021-04-10 03:23:29
【问题描述】:
这是我使用经典凯撒密码进行暴力破解的代码。蛮力解密显示出奇怪的结果,因为当我将密钥设置为 3 时,它会多次发布相同的解密字符串。在其他密钥中,例如 7,它甚至不显示正确的解密字符串。
我的蛮力解密方法是根据字母表改变加密消息中的每个字母,因此有一个26次的for循环,以及另一个消息长度的for循环。它使用 StringBuilder 的 setCharAt 方法来改变字符串中的字符。
这是我仅使用暴力破解的代码:
void decryptbruteforce(String encryptmessage) {
//Get the standard alphabet
String standalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//Convert this message to uppercase
String encryptmessageupper = encryptmessage.toUpperCase();
StringBuilder sbdecrypt = new StringBuilder(encryptmessageupper);
int key;
int i;
int index;
char currentchar;
char newchar;
//Loop through the 26 keys in the alphabet.
for (key = 1; key < 27; key++) {
//Loop through the encrypted message
for (i = 0; i < sbdecrypt.length(); i++) {
//Get the encrypted character
currentchar = sbdecrypt.charAt(i);
//Get the index in the alphabet
index = standalpha.indexOf(currentchar);
//If the currentchar is in the alphabet
if (index != -1) {
//Reduce the character by the key in the alphabet
index = index - key;
//If the character goes below 0, aka 'A', go back to the end of the alphabet
if (index < 0) {
index = index + 26;
//Get the new character in the alphabet
newchar = standalpha.charAt(index);
//Set the character in the stringbuilder
sbdecrypt.setCharAt(i, newchar);
}
else {
//Get the new character in the alphabet
newchar = standalpha.charAt(index);
//Set the character in the stringbuilder
sbdecrypt.setCharAt(i, newchar);
}
}
}
//Print the key and the resulting string
System.out.println("Key: " + key + " Decrypted String: " + sbdecrypt);
}
}
这是我的输出: Caesar Cipher key of 3 Caesar Cipher key of 7
如果有帮助,这是我的整个代码的链接:https://gist.github.com/cliven-hew/35e9458c24d5f5b1ace97b7146ec429a
【问题讨论】:
-
将控制台结果放在文本中会很有帮助,类似于您的代码而不是图像链接。
-
好的,谢谢提醒!
标签: java encryption caesar-cipher