Link to home
Start Free TrialLog in
Avatar of sriramvemaraju2000
sriramvemaraju2000

asked on

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

Avatar of Peter Kwan
Peter Kwan
Flag of Hong Kong image

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



Avatar of sriramvemaraju2000
sriramvemaraju2000

ASKER

no I need for every ascii character .. I need to encrypt the binary files as well.
What error do you get for k>3 then?
ASKER CERTIFIED SOLUTION
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial