一次性垫每次都给出相同的答案

时间:2014-04-30 21:13:19

标签: java encryption-symmetric

我正在用Java编写一次性填充加密程序。即使使用新的随机密钥,程序也会输出相同的“解密”文本 这是加密代码:

public static String oneTimePad(String plaintext, int[] key) {
    int a = 0;
    char[] ciphertext = plaintext.toUpperCase().toCharArray();
    for (int i = 0; i < plaintext.length(); i++) {
        if (ciphertext[i] < 'A' || ciphertext[i] > 'Z') {
        } else {
            ciphertext[i] = (char) ((((plaintext.charAt(i) - 65) + key[a]) % 26) + 65);
            a++;
        }
    }
    return new String(ciphertext);
}

这是解密代码:

public static String padDecrypt(String ciphertext, int[] key) {
    char[] plaintext = ciphertext.toUpperCase().toCharArray();
    for (int i = 0, a = 0; i < ciphertext.length(); i++) {
        if (plaintext[i] < 'A' || plaintext[i] > 'Z')
            continue;
        int x = (ciphertext.charAt(i) - 65) - key[a];
        if (x < 0)
            x += 26;
        plaintext[i] = (char) ((x % 26) + 90);
        a++;
    }
    return new String(plaintext).toLowerCase();
}

字符串“这是有史以来最聪明的程序”的结果 加密文字:

IYDS PJ UNN SIMZGQHZ UZRMODJ SWAM WOFM

关键的例子:

9, 11, 15, 20, 1, 11, 21, 0, 3, 20, 16, 6, 2, 7, 6, 9, 0, 25, 2, 23, 0, 17, 23, 17, 8, 21, 16, 15, 4, 8, 22, 2, 17, 16, 23, 21, 4, 9

这是“即使使用不同的密钥也不会改变的解密文本:

 sghr hr sgd rl`qsdrs oqnfq`l d[dq l`cd

如果有人可以给我一些很棒的建议!

1 个答案:

答案 0 :(得分:0)

好的两种方法一起使用,我发现代码有两个问题:

  1. oneTimePad假定输入为大写。明文是小写的。我认为那里可能存在不匹配。
  2. ASCII 90是&#39; Z&#39;。我想你可能意味着97这是&#39; a&#39;。我建议你用他们的角色代替号码......而不是65岁使用&#39; A&#39;。
相关问题