Question

I was trying to print encrypted text using string perhaps i was wrong somewhere. I am doing simple xor on a plain text. Coming encrypted text/string i am putting in a C program and doing same xor again to get plain text again.

But in between, I am not able to get proper string of encrypted text to pass in C

String xorencrypt(byte[] passwd,int pass_len){
    char[] st = new char[pass_len];
    byte[] crypted = new byte[pass_len];
    for(int i = 0; i<pass_len;i++){
        crypted[i] = (byte) (passwd[i]^(i+1));
        st[i] = (char)crypted[i];
        System.out.println((char)passwd[i]+" "+passwd[i] +"= " + (char)crypted[i]+"   "+crypted[i]);/* characters are printed fine but problem is when i am convering it in to string */
    }
    return st.toString();
}    

I don't know if any kind of encoding also needed because if i did so how I will decode and decrypt from C program.

example if suppose passwd = bond007

then java program should return akkb78>

further C program will decrypt akkb78> to bond007 again.

Was it helpful?

Solution

Use

return new String(crypted);

in that case you don't need st[] array at all.

By the way, the encoded value for bond007 is cmm`560 and not what you posted.

EDIT
While solution above would most likely work in most java environments, to be safe about encoding, as suggested by Alex, provide encoding parameter to String constructor. For example if you want your string to carry 8-bit bytes :

return new String(crypted, "ISO-8859-1");

You would need the same parameter when getting bytes from your string :

byte[] bytes = myString.getBytes("ISO-8859-1")


Alternatively, use solution provided by Alex :

return new String(st);

But, convert bytes to chars properly :

st[i] = (char) (crypted[i] & 0xff);

Otherwise, all negative bytes, crypted[i] < 0 will not be converted to char properly and you get surprising results.

OTHER TIPS

Change this line:

return st.toString();

with this

return new String(st);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top