gpt4 book ai didi

Java凯撒密码暴力破解

转载 作者:行者123 更新时间:2023-12-01 12:59:59 24 4
gpt4 key购买 nike

我是 Java 新手,我需要编写一个算法来使用强力破解凯撒密码,然后匹配字典中的单词以找到正确的移位。这就是我到目前为止编写的代码。如果有人帮助我实现移动字母并将其与文件dictionary.txt 进行匹配,我将非常感激。

private char[] alphabet = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
private char[] decodedText;
private String plainText;

public String producePlaintext(String cipherText) {
//put each letter of the ciphertext in an array of characters in the upper case format
char[] message = cipherText.toUpperCase().toCharArray();
//loop through all the possible keys
for (int key = 0; key < alphabet.length; key++) {
//set the value of the decrypted array of characters to be the same as the length of the cipher text
decodedText = new char[message.length];
//loop through the characters of the ciphertext
for (int i = 0; i < message.length; i++) {

//if character is not space
if (message[i] != ' ') {
//shift the letters

}else{
decodedText[i] = ' ';
}
}
plainText = String.valueOf(decodedText);
}
return plainText;
}

最佳答案

您需要将字母数组转换为 List 才能使用 indexOf 方法:

private List<Character> alphabetList = java.util.Arrays.asList(alphabet);

在里面您可以执行以下操作:

decodedText[i] = alphabet[(alphabetList.indexOf(message[i])+key) % alphabet.length];

您可能应该以 1 而不是 0 开始 key 的迭代,因为这样您将只得到密文。

完整的解决方案:

public class Test01 {

private Character[] alphabet = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
private char[] decodedText;
private String[] plainText;
private java.util.List<Character> alphabetList;

public Test01(){
alphabetList = java.util.Arrays.asList(alphabet);
plainText = new String[alphabet.length];
}

public String[] producePlaintext(String cipherText) {
//put each letter of the ciphertext in an array of characters in the upper case format
char[] message = cipherText.toUpperCase().toCharArray();
//loop through all the possible keys
for (int key = 0; key < alphabet.length; key++) {
//set the value of the decrypted array of characters to be the same as the length of the cipher text
decodedText = new char[message.length];
//loop through the characters of the ciphertext
for (int i = 0; i < message.length; i++) {

//if character is not space
if (message[i] != ' ') {
//shift the letters
decodedText[i] = alphabet[(alphabetList.indexOf(message[i])+key) % alphabet.length];
}else{
decodedText[i] = ' ';
}
}
plainText[key] = String.valueOf(decodedText);
}
return plainText;
}

public static void main(String[] args) {
Test01 t = new Test01();
for(String pt : t.producePlaintext("abc")) {
System.out.println(pt);
}
}

}

注意字符类型的差异。

关于Java凯撒密码暴力破解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23582694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com