凯撒密码的蛮力解密
Posted
技术标签:
【中文标题】凯撒密码的蛮力解密【英文标题】:Brute force decryption for a Caesar Cipher 【发布时间】: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
【问题讨论】:
将控制台结果放在文本中会很有帮助,类似于您的代码而不是图像链接。 好的,谢谢提醒! 【参考方案1】:您的问题是您总是在编辑同一个StringBuilder sbdecrypt
对象。因此,当您使用键 1 进行移位时,您的下一次尝试不是基于移位原始字符串,而是基于先前移位的字符串。这就是为什么您在跳过 M....
的同时从 N....
转到 L....
并且这种模式一直持续的原因。
您可以通过在 for (key = 1; key < 27; key++)
行后添加 sbdecrypt = new StringBuilder(encryptmessageupper);
来解决此问题。
public static void decryptbruteforce(String encryptmessage)
String standalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String encryptmessageupper = encryptmessage.toUpperCase();
StringBuilder sbdecrypt = new StringBuilder(encryptmessageupper);
int key;
int i;
int index;
char currentchar;
char newchar;
for (key = 1; key < 27; key++)
//Ensure you do your shift on the same string each time.
//This makes a new object each time
sbdecrypt = new StringBuilder(encryptmessageupper);
for (i = 0; i < sbdecrypt.length(); i++)
currentchar = sbdecrypt.charAt(i);
index = standalpha.indexOf(currentchar);
if (index != -1)
index = index - key;
if (index < 0)
index = index + 26;
newchar = standalpha.charAt(index);
sbdecrypt.setCharAt(i, newchar);
System.out.println("Key: " + key + " Decrypted String: " + sbdecrypt);
【讨论】:
感谢您解决此问题!代码现在运行良好。以上是关于凯撒密码的蛮力解密的主要内容,如果未能解决你的问题,请参考以下文章