0

Right now I have the following code for a Caesar Cipher, but I run into an issue when I try encrypting text with a very large number. For example 1000.

static String encrypt(String plaintext) {
    StringBuilder ciphertext = new StringBuilder(plaintext);
    for (int i = 0; i < ciphertext.length(); i++) {
        ciphertext.setCharAt(i, encrypt(ciphertext.charAt(i)));
    }
    return ciphertext.toString();
}

static String decrypt(String plaintext) {
    StringBuilder ciphertext = new StringBuilder(plaintext);
    for (int i = 0; i < ciphertext.length(); i++) {
        ciphertext.setCharAt(i, decrypt(ciphertext.charAt(i)));
    }
    return ciphertext.toString();
}

static char encrypt(char c) {
    return (char) ('!' + (c - '!' + 1000) % ('~' - '!' + 1));
}

static char decrypt(char c) {
    return (char) ('!' + (c - '!' - 1000) % ('~' - '!' + 1));
}

Lets say I input "abc123" into the encryption, using 1000 as my key, I get a bunch of unknown characters. Keep in mind I don't want it to just cycle through a-z but symbols too, using ASCII codes.

Any help would be great!

Parth Satra
  • 513
  • 2
  • 16
Arman
  • 655
  • 2
  • 7
  • 23
  • Link to ASCII Table I'm using: http://www.asciitable.com/ – Arman Nov 05 '14 at 23:28
  • Since you only want to map on the visible ascii characters, 126-33+1=94 possible values. Any key above 93 will have a corresponding smaller key that will do the same thing. 95 will encrypt the same as 1, 0 as 94 etc so a large value like 1000 is unnecessary. – ryanpattison Nov 05 '14 at 23:40
  • @rpattiso Even if I use 93 in place of 1000 I still get unknown characters, or nonvisible characters. – Arman Nov 05 '14 at 23:44

1 Answers1

1

In Java, the result of modulo is the same sign as the dividend. So when you compute c - '!' - 1000 you will get a negative value and after the modulo it will still be negative. When you add '!', you will have computed a values less than '!', which will be invisible or underflow for a char.

static char decrypt(char c) {
    char d = '~' - '!' + 1;
    int x = (c - '!' - 1000) % d;
    if (x < 0) x += d;
    return (char)('!' + x);
}

Here is a discussion for the problem your running into.

How does java do modulus calculations with negative numbers?

Community
  • 1
  • 1
ryanpattison
  • 6,151
  • 1
  • 21
  • 28