4

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

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);
}
4

1 回答 1

3

您应该创建ciphertextwithnew String(chars)而不是chars.toString()

ciphertext = new String(chars);
于 2012-12-21T13:53:32.640 回答