6

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.

Max Canlas
  • 61
  • 1
  • 1
  • 2

7 Answers7

8

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].

Pascal T.
  • 3,866
  • 4
  • 33
  • 36
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

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

}

Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219
1

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

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
1

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
  • 66,304
  • 38
  • 162
  • 239
1

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
  • 11
  • 1
1

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

Obscure
  • 11
  • 1
0
import java.util.Scanner;
//caeser

public class Major_Assingment {

public static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZhh";

public static String encrypt(String plainText,int shiftKey)
{

plainText = plainText.toUpperCase();

    String cipherText= " ";

    for(int i=0; i<plainText.length(); i++)
    {

        int charPosition = ALPHABET.indexOf(plainText.charAt(i));

        int keyVal = (shiftKey + charPosition)% 26 ;

        char replaceVal = ALPHABET.charAt(keyVal);

        cipherText += replaceVal;
        }

    return cipherText;
}

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the string for Encryption:");

        String message = new String();

        message = sc.next();

        System.out.println(encrypt(message,3));

        sc.close();

    }

}
Dom
  • 1,687
  • 6
  • 27
  • 37