I'm trying to do a server client communication using UDP and it involves sending encrypted text using RC4 to each other. It goes something like this:
Start Host.
Start Client.
Client sends encrypted text using RC4
Host receive encrypted text and decrypt using RC4
My RC4 is taken from an online source and it seems to be working. If I were to do both encryption and decryption on client side (for testing purpose), it works. But the problem occurs after I sent my encrypted text over to the host. When my host decrypts the message the output isn't the expected output.
Here is an example of my code on client:
RC4 rc4 = new RC4(rc4Key);
String message = "Hello";
char[] result = rc4.encrypt(message.toCharArray());
System.out.println("encrypted string: " + new String(result)); //M®FW?
System.out.println("decrypted string: " + new String(rc4.decrypt(result))); //Hello
From the above, I assume my RC4 is working because I seem to be able to encrypt and decrypt properly. So now I send the encrypted text over to my host
sentence = new String(result);
sendData = sentence.getBytes();
sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
And on my host side, I will be receiving the encrypted text
receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
realSentence = Arrays.copyOf(receivePacket.getData(), receivePacket.getLength());
sentence = new String(realSentence);
RC4 rc4 = new RC4(ad.toString());
char[] result = rc4.decrypt(sentence);
System.out.println("decrypted string: " + new String(result)); //H?ll?
This occurs only half the time, and I'm seeing a pattern that it only occurs when my encrypted text contains ?
as a special character. So I'm guessing that when I convert char to string and then to byte and send over through UDP, something went wrong.