Question

I am writing a one time pad encryption program in Java. The program outputs the same "decrypted" text even with a new randomized key.
Here is the encryption code:

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

Here is the decryption code:

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

Results for the string "this is the smartest program ever made"
Encrypted text:

IYDS PJ UNN SIMZGQHZ UZRMODJ SWAM WOFM

The key example:

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

Here is the "decrypted text that never changes even with different keys:

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

If someone could give me some advice that would be great!

Was it helpful?

Solution

Ok the two methods taken together, I see two problems wrong with the code:

  1. oneTimePad assumes that the input is uppercase. The plaintext is lower case. I think there could be a mismatch there.
  2. ASCII 90 is 'Z'. I think you might mean 97 which is 'a'. I recommend you replace the numbers with their characters anyway ... instead of 65 use 'A'.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top