用CaesarCipherBreaker拆分字符串

时间:2016-01-09 01:31:26

标签: java encryption

如何为此示例添加代码以创建CaesarCipherBreaker方法,该方法通过两个键拆分加密的消息。到目前为止,我写了这么多:

foo

警告:此行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);也有构造函数错误。

我现在的breakCaesarCipher方法只计算出一个键,而不是两个。我该如何编写一个拆分加密字符串的方法,找出用于解密的两个密钥。

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的代码,您可以拨打halfOfString(两次)来获取密文的两部分,然后使用您通常的方法分别打破两个部分的Ceaser-Cipher。 / p>

您的错误似乎是因为双密钥加密需要(不出所料)两个密钥。你应该把它们都给构造函数。

public String breakCaesarCipher(String input) {
    String in_0 = halfOfString(input, 0);
    String in_1 = halfOfString(input, 1);
    // Find first key
    // Determine character frequencies in ciphertext
    int[] freqs_0 = countOccurrencesOfLetters(in_0);
    // Get the most common character
    int freqDex_0 = maxIndex(freqs_0);
    // Calculate key such that 'E' would be mapped to the most common ciphertext character
    // since 'E' is expected to be the most common plaintext character
    int dkey_0 = freqDex_0 - 4;
    // Make sure our key is non-negative
    if (dkey_0 < 0) {
        dkey_0 = dkey_0+26;
    }
    // Find second key
    int[] freqs_1 = countOccurrencesOfLetters(in_1);
    int freqDex_1 = maxIndex(freqs_1);
    int dkey_1 = freqDex_1 - 4;
    if (freqDex_1 < 4) {
        dkey_1 = dkey_1+26;
    }

    CaesarCipherTwoKeys cctk = new CaesarCipherTwoKeys(dkey_0, dkey_1);
    return cctk.decrypt(input);
}