java语言密文中的凯撒密码失败

时间:2012-12-21 13:50:30

标签: java encryption

我用Java语言制作caesar密码加密器,这是我的代码

private void encCaesar() {
    tempCipher = "abcdef";
    char[] chars = tempCipher.toCharArray();
    for (int z = 0; z < tempCipher.length(); z++) {
        char c = chars[z];
        if (c >= 32 && c <= 126) {
            int x = c - 32;
            x = (x + keyCaesar) % 96;
            if (x < 0)
                x += 96;
            chars[z] = (char) (x + 32);
        }
    }
    ciphertext = chars.toString();
    etCipher.setText(ciphertext);
}

我找不到任何错误,但密文是这样的 405888,这是明文是“abcdef”而默认密钥是3的废话

怎么了?

正确:

private void encCaesar() {
    tempCipher = "abcdef";
    char[] chars = tempCipher.toCharArray();
    for (int z = 0; z < tempCipher.length(); z++) {
        char c = chars[z];
        if (c >= 32 && c <= 126) {
            int x = c - 32;
            x = (x + keyCaesar) % 96;
            if (x < 0)
                x += 96;
            chars[z] = (char) (x + 32);
        }
    }
    ciphertext = new String(chars);
    etCipher.setText(ciphertext);
}

1 个答案:

答案 0 :(得分:3)

您应该使用ciphertext代替new String(chars)创建chars.toString()

ciphertext = new String(chars);