My java class implementation of XOR encryption has gone wrong -



My java class implementation of XOR encryption has gone wrong -

i new java fluent in c++ , c# c#. know how xor encryption in both c# , c++. problem algorithm wrote in java implement xor encryption seems producing wrong results. results bunch of spaces , sure wrong. here class below:

public final class encrypter { public static string encryptstring(string input, string key) { int length; int index = 0, index2 = 0; byte[] ibytes = input.getbytes(); byte[] kbytes = key.getbytes(); length = kbytes.length; char[] output = new char[ibytes.length]; for(byte b : ibytes) { if (index == length) { index = 0; } int val = (b ^ kbytes[index]); output[index2] = (char)val; index++; index2++; } homecoming new string(output); } public static string decryptstring(string input, string key) { int length; int index = 0, index2 = 0; byte[] ibytes = input.getbytes(); byte[] kbytes = key.getbytes(); length = kbytes.length; char[] output = new char[ibytes.length]; for(byte b : ibytes) { if (index == length) { index = 0; } int val = (b ^ kbytes[index]); output[index2] = (char)val; index++; index2++; } homecoming new string(output); } }

strings in java unicode - , unicode strings not general holders bytes ascii strings can be.

you're taking string , converting bytes without specifying character encoding want, you're getting platform default encoding - us-ascii, utf-8 or 1 of windows code pages.

then you're preforming arithmetic/logic operations on these bytes. (i haven't looked @ you're doing here - know algorithm.)

finally, you're taking these transformed bytes , trying turn them string - is, characters. again, haven't specified character encoding (but you'll same got converting characters bytes, that's ok), but, importantly...

unless platform default encoding uses single byte per character (e.g. us-ascii), not of byte sequences generate represent valid characters.

so, 2 pieces of advice come this:

don't utilize strings general holders bytes always specify character encoding when converting between bytes , characters.

in case, might have more success if give us-ascii encoding. edit: lastly sentence not true (see comments below). refer point 1 above! utilize bytes, not characters, when want bytes.

java encryption xor

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -