java使用解压器拆分字符串
我将如何在这个示例中添加代码,以创建将加密消息拆分为两个密钥的CaesarCipherBreaker方法。到目前为止,我已经写了很多:
import edu.duke.*;
public class TestCaesarCipherTwo {
public int[] countOccurrencesOfLetters(String message) {
//snippet from lecture
String alph = "abcdefghijklmnopqrstuvwxyz";
int[] counts = new int[26];
for (int k=0; k < message.length(); k++) {
char ch = Character.toLowerCase(message.charAt(k));
int dex = alph.indexOf(ch);
if (dex != -1) {
counts[dex] += 1;
}
}
return counts;
}
public int maxIndex(int[] values) {
int maxDex = 0;
for (int k=0; k < values.length; k++) {
if (values[k] > values[maxDex]) {
maxDex = k;
}
}
return maxDex;
}
public String halfOfString(String message, int start) {
StringBuilder halfString = new StringBuilder();
for (int index=start;index < message.length();index += 2) {
halfString.append(message.charAt(index));
}
return halfString.toString();
}
public void simpleTests() {
FileResource fileResource = new FileResource();
String fileAsString = fileResource.asString();
CaesarCipherTwoKeys cctk = new CaesarCipherTwoKeys(17, 3);
String encrypted = cctk.encrypt(fileAsString);
System.out.println("Encrypted string:\n"+encrypted);
String decrypted = cctk.decrypt(encrypted);
System.out.println("Decrypted string:\n"+decrypted);
String blindDecrypted = breakCaesarCipher(encrypted);
System.out.println("Decrypted string using breakCaesarCipher():\n"+blindDecrypted);
}
public String breakCaesarCipher(String input) {
int[] freqs = countOccurrencesOfLetters(input);
int freqDex = maxIndex(freqs);
int dkey = freqDex - 4;
if (freqDex < 4) {
dkey = 26 - (4-freqDex);
}
CaesarCipherTwoKeys cctk = new CaesarCipherTwoKeys(dkey);
return cctk.decrypt(input);
}
}
警告:我在这一行CaesarCipherTwoKeys cctk = new CaesarCipherTwoKeys(dkey);
上还有一个构造函数错误,说明CaesarCipherTwoKeys in class CaesarCipherTwoKeys cannot be applied to given types; required int,int; found int...
我现在使用的密码方法只能算出一个密钥,而不是两个。我应该如何编写一个方法来拆分加密字符串,找出用于解密的两个密钥
# 1 楼答案
如果我正确理解了你的代码,你可以直接调用
halfOfString
(两次)来获取密文的两部分,然后使用你通常的方法分别破解两部分的凯瑟密码您的错误似乎是由于双密钥加密需要(不出所料)两个密钥。你应该把它们都交给构造器