views:

496

answers:

2

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?

+8  A: 

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

Jon Skeet
+1. @NewJavaProgrammer- The base64 isn't encrypted either, it is however encoded.
RichardOD
@RichardOD - actually the base64 produced by @Jon's method is both encoded AND encrypted.
Stephen C
Yeah- I somehow didn't see the "apply your encryption" bit. Too early in the morning!
RichardOD
A: 

1st of all, don't call XORing encryption. Seriously, the CipherOutputStream and CipherInputStream are there for you if you need to protect your data.

Thanks for stream chaining, you can have DataOutputStream -> CipherOutputStream -> ByteArrayOutputStream. This will get you properly encrypted bytes. Use the reverse APIs on the other end and you'll get your string back.

mlaverd