Java string to bytearray back to string
arrays, string, xor
Solution
After you've applied something like XOR, you end up with arbitrary binary data - not an encoded string.
The conventional safe way to convert arbitrary binary into text is to use base64 - don't try to just create a new string from it. So your process would be something like this:
- Start with plain text as a string.
- Encode the plain text using UTF-8, UTF-16 or something similar. Don't use the platform default encoding, or anything restrictive like ASCII. You now have a byte array.
- Apply your encryption. (XOR is pretty weak, but let's leave that to one side.) You still have a byte array.
- Apply base64 encoding to get a string.
Then when you need to decrypt...
- Apply base64 decoding to convert your string into a byte array.
- Apply your binary decryption process (e.g. XOR again). You still have a byte array.
- Now decode that byte array into a string, e.g. with `new String(data, utf8Charset)` to get back the original string.
There are various Java base64 libraries available, such as this class in Apache Commons Codec. (You'd want the `encodeToString(byte[])` and `decode(String)` methods.)
Problem
I have a client and server java application that needs have encrypted text passing through each other. I am using an XOR encryption the encrypt the text that I want. The problem is that readline() doesn't accept string that has been XORed and will only if accepted if it is in bytes. So I've converted my plaintext (string) into a byte array on the client side, and tried to convert back to a string on the server side. Sadly, the result I am looking for is still jibberish and not the plaintext that I seeked. Does anyone know how to make bytearrays change back to the original string? Or is there a better way to send through an XOR encrypted text through the readline() function?