如何从调用方法获取键值

时间:2016-01-12 04:56:18

标签: java encryption

所以在我的方法simpleTests类TestCaesarCipherTwo中我调用另一个方法,breakCaeserTwo来执行加密消息的解密。我也希望有相同的breakCaesarTwo方法用于找出解密中使用的密钥。现在我的代码看起来像这样:

 public void simpleTests()
    {
        int key1 = 17;
        int key2 = 3;
        FileResource fr = new FileResource();
        String message = fr.asString();
        CaesarCipherTwoKeys cctk = new CaesarCipherTwoKeys(key1, key2);
        String encrypted = cctk.encrypt(message);
        System.out.println(encrypted);

        String decrypted = cctk.decrypt(encrypted);
        System.out.println(decrypted);

        BreakCaesarThree bct = new BreakCaesarThree();
        String broken = breakCaesarTwo(encrypted);
        System.out.println("Keys found: " + bct.dkey_0 + ", " + bct.dkey_1 + "\n" + broken);    
  }

我有Keys found: " + bct.dkey_0 + ", " + bct.dkey_1 + "\n" + broken使用BreakCaesarThree(bct)的实例来获取密钥。当我将方法breakCaesarTwo调用simpleTests时,我的加密和解密代码似乎才有用。所以我现在的问题是如何调用方法并使用它来获取加密密钥,就像我使用" .bct"

找到BreakCaesarThree的密钥时

注意:我不想在我的代码中使用BreakCaesarThree或它的任何实例。我想直接引用代码中已有的breakCaesarTwo方法。我想知道是否有办法调用此方法并获取键值,就像我使用BreakCaesarThree一样,使用" .bct"。这种改变的语法是什么?   这是方法breakCaesarTwo的代码:

public String breakCaesarTwo(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);
  }

1 个答案:

答案 0 :(得分:0)

创建一个帮助程序类,例如:

public class DecryptionResult {
    String decryptedValue;
    String key1;
    String key2;

    public DecryptionValue(String decryptedValue, String key1, String key2) {
        this.decryptedValue = decryptedValue;
        this.key1 = key1;
        this.key2 = key2;
    }

    public String getDecryptedValue() {
        return decryptedValue;
    }

    public String getKey1() {
        return key1;
    }

    public String getKey2() {
        return key2;
    }
}

...并让您的breakCaesarTwo方法返回DecryptionResult的实例:

public DecryptionResult breakCaesarTwo(String input) {
    ...
    CaesarCipherTwoKeys cctk = new CaesarCipherTwoKeys(dkey_0, dkey_1);
    return new DecryptedResult(cctk.decrypt(input), dkey_0, dkey_1);
}