Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple caesar cipher in java

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.

like image 298
Max Canlas Avatar asked Nov 30 '09 18:11

Max Canlas


6 Answers

How about something like this:

public String applyCaesar(String text, int shift)
{
    char[] chars = text.toCharArray();
    for (int i=0; i < text.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;
            if (x < 0) 
              x += 96; //java modulo can lead to negative values!
            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].

like image 192
Jon Skeet Avatar answered Oct 24 '22 09:10

Jon Skeet


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

like image 44
Andreas Dolk Avatar answered Oct 24 '22 07:10

Andreas Dolk


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!

like image 30
rook Avatar answered Oct 24 '22 08:10

rook


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!

like image 27
Rodolfo Avatar answered Oct 24 '22 07:10

Rodolfo


Why not try

for(int i = 0; i < length; i++) { char c = chars[i] if(Character.isLetter(c)) { int x = c - 32; x = (x + shift) % 96; chars[i] = (char) (x+32); } }

like image 1
Obscure Avatar answered Oct 24 '22 08:10

Obscure


Copy paste this in NetBeans with name "caesar":

    //package caesar;
    import java.io.*;

    public class caesar {

    int offset=3;
    public String encrypt(String s) throws IOException
    {
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<s.length();i++)
        {
            char t=s.charAt(i);
            if(t>='A' && t<='Z')
            {
                int t1=t-'A'+offset;
                t1=t1%26;
                sb.append((char)(t1+'A'));
            }
            else if(t>='a' && t<='z')
            {
                int t1=t-'a'+offset;
                t1=t1%26;
                sb.append((char)(t1+'a'));
            }
        }
        return sb.toString();
    }


    public String decrypt(String s) throws IOException
    {
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<s.length();i++)
        {
            char t=s.charAt(i);
            if(t>='A' && t<='Z')
            {
                int t1=t-'A'-offset;
                if(t1<0)t1=26+t1;
                sb.append((char)(t1+'A'));
            }
            else if(t>='a' && t<='z')
            {
                int t1=t-'a'-offset;
                if(t1<0)t1=26+t1;
                sb.append((char)(t1+'a'));
            }
        }
        return sb.toString();
    }


public static void main(String[] args) {
try
{
    System.out.println("Caesar encrypion technique");
    BufferedReader b;
    String oriTxt,encTxt,decTxt;
    System.out.println("Enter string to encrypt:");
    b=new BufferedReader(new InputStreamReader(System.in));
    oriTxt=b.readLine();
    caesar c=new caesar();
    encTxt=c.encrypt(oriTxt);
    System.out.println("Encrypted text :"+encTxt);
    decTxt=c.decrypt(encTxt);
    System.out.println("Derypted text :"+decTxt);
}
catch(Exception e)
{
    System.out.println(e.toString());
}
}

}

like image 1
xameeramir Avatar answered Oct 24 '22 08:10

xameeramir