I have problem decrypting message from send from my client and I keep on getting BadpaddingException error. The message is sent and receive in byte form using Data output stream write(byte) and the inputstream read(byte, offset, length) method from client to my server as advised by a fellow rancher from my another topic.
I would like to know am I doing the decryption the right way? Or doing I have to method overloading for my decryption method?
I am not sure whether am I using the byte buffer correctly too. Can someone please advise me on how to solve this problem? Thanks and Appreciate any help in advance.
I did my decryption in this way as I am trying to make my driver work with both TCP and UDP java coding.
The length you should be using in your decrypt() is the 'length' returned by the connectionSocket.getInputStream().read(buffer, 0, buffer.length) and not the buffer length!
Note - if your buffer is not long enough to hold the whole of your ciphertext or if the read of the socket input stream does not return the whole ciphertext in one read (it does not have to according to the specification for InputSteam) then your code will fail. You should loop using one of the Cipher.update() method until you have read all your ciphertext.
Also, I do not see how you know that you have read all the ciphertext since unless the socket closes for each message you will not get an eof indication. The normal approach to this is to prefix each ciphertext with the length of the ciphertext. DataInputStream and DataOutputStream are very useful for this.
Since they offer significant advantages when dealing with TCP socket encryption you might want to take a look at stream ciphers such as RC4 with CipherInputStream and CipherOutputStream (any block cipher such as AES can be turned into a stream cipher). You might also want to take a look at using ephemeral keys using something like Diffe-Hellman since the use of ephemeral key makes the things more secure (even if the key for one message is found it is no use in helping to decrypt other messages). Finally, the preferred way and probably the easiest way to handle TCP stream encryption is to use SSL/TLS using JSSE when all the hard work associated with encryption and key exchange is done for you.