We help IT Professionals succeed at work.

what is wrong in my code: substitution cipher java

I tried to develop substitution cipher .. But it is giving me error if I took the value greater than 3... I donno why ...
please help me in correcting the code...

import java.io.UnsupportedEncodingException;

public class DataUtility {

    public static String encryptMessage(String msg, int k) throws UnsupportedEncodingException {
        String value = "";
        byte bt1[] = msg.getBytes();
        for (int i = 0; i < bt1.length; i++) {
            //System.out.println(bt[i]);
            value += encryptByte(bt1[i], k);
        }
        System.out.println(value);
        return value;
    }
    public static char encryptByte(byte c, int k) {

        return (char) ((c + k));
    }

    public static byte encryptByteAsByte(byte c, int k) {

        return (byte) ((c + k));
    }

    public static String decryptMessage(String msg, int k) throws UnsupportedEncodingException {
        String result = "";
        byte[] bt = msg.getBytes();
        for (int i = 0; i < bt.length; i++) {
            result += decryptByte(bt[i], k);
        }
        System.out.println(result);
        return result;
    }

    public static char decryptByte(byte c, int k) {
        return (char) ((c - k));
    }

    public static byte decryptByteAsByte(byte c, int k) {

        System.out.println("c=" + c + ",k=" + k);
        return (byte) ((c - k));
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        encryptMessage("doctype", 8);
        decryptMessage("lwk|xm", 8);
    }
}

Open in new window

Comment
Watch Question

Peter KwanAnalyst Programmer

Commented:
May I know whether you are going to limit the plain-text and encrypted words to lower-case alphabets only? If yes, you should add mod 26 to your encryption/decryption logic.
Peter KwanAnalyst Programmer

Commented:
A sample update of your encryption code:

    public static char encryptByte(byte c, int k) {

        return (char) ((c - 'a' + k) % 26 + 'a');
    }

For decryption, it is similar, but you should add +26 before you subtract in order not to overflow if c is less than k.



Author

Commented:
no I need for every ascii character .. I need to encrypt the binary files as well.
Peter KwanAnalyst Programmer

Commented:
What error do you get for k>3 then?
Awarded 2010
Top Expert 2013
Commented:
In Java the char type is 2 bytes and is Unicode. When you do c+k it will add them as integers and then convert to char. So if the number is too large it will not wrap but will use special characters.

Also, bytes are signed in Java.
Try changing line 17 to
return (char) ((c+128 + k)%256);

+128 to convert to unsigned byte and %256 to wrap overflow.
Of course then line 36 would be
return (char) ((c+128 - k + 256)%256);

The +256 is to make sure you don't do % on negative numbers. You might be able to leave it out depending on how Java handles them.