Trutone
Trutone

Reputation: 59

Caesar cipher in java language ciphertext fail

Im making caesar cipher encryptor in Java language, here is my code

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

I cant find anything wrong, but the ciphertext is something like this 405888, which is nonsense where the plaintext is "abcdef" and default key is 3

What's wrong?

correct :

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

Upvotes: 4

Views: 871

Answers (1)

Aviram Segal
Aviram Segal

Reputation: 11120

You should create the ciphertext with new String(chars) instead of chars.toString():

ciphertext = new String(chars);

Upvotes: 3

Related Questions