views:

1335

answers:

4

Hey I'm making a simple caesar cipher in Java using the formula [x-> (x+shift-1) mod 127 + 1] I want to have my encrypted text to have the ASCII characters except the control characters(i.e from 32-127). How can I avoid the control characters from 0-31 applying in the encrypted text. Thank you.

+2  A: 

How about something like this:

public String applyCaesar(String text, int shift)
{
    char[] chars = text.toCharArray();
    for (int i=0; i < length; i++)
    {
        char c = chars[i];
        if (c >= 32 && c <= 127)
        {
            // Change base to make life easier, and use an
            // int explicitly to avoid worrying... cast later
            int x = c - 32;
            x = (x + shift) % 96;
            chars[i] = (char) (x + 32);
        }
    }
    return new String(chars);
}

Admittedly this treats 127 as a non-control character, which it isn't... you may wish to tweak it to keep the range as [32, 126].

Jon Skeet
A: 

Map your characters from [32..127] to [0..95], do a mod 95+1 and map the result back to [32..127].

Andreas_D
-1 And what about the control characters?
Todd Owen
A: 

Usually cipher text is base64 encoded, base16 (hex) also works well. Base64 is used most often for cipher text because it takes up less space than hex, hex is most commonly used for message digests. In the java.util.prefs.Base64 library you will find byteArrayToBase64() and base64ToByteArray().

On a side note you should NEVER write your own encryption algorithm for security reasons, you should be using a block cipher or stream cipher. I hope this is for fun!

Rook
A: 

Hi, there! Is there any way to consider the whole range of characters? For example, "á", "é", "ö", "ñ", and not consider " " (the [Space])? (For example, my String is "Hello World", and the standard result is "Khoor#Zruog"; I want to erase that "#", so the result would be "KhoorZruog")

I'm sure my answer is in this piece of code:

if (c >= 32 && c <= 127)
        {
            // Change base to make life easier, and use an
            // int explicitly to avoid worrying... cast later
            int x = c - 32;
            x = (x + shift) % 96;
            chars[i] = (char) (x + 32);
        }

... But I've tried some things, and the didn't work :S So, I'll wait for your answers :D See you!

Rodolfo