i am writing an application where i transfer a byte array over a socket in java.
The generation of byte array at the client end is as follows:
String vote = br.readLine();
// the data that i now encrypt using RSA
PublicKey pubKey = readKeyFromFilepublic("alicepublic.txt");
Cipher cvote = Cipher.getInstance("RSA");
cvote.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] voted = cvote.doFinal(vote.getBytes());
System.out.println(voted);
out.println(voted.length);
dos.write(voted,0,voted.length); // here i am sending the array to the server
on the server side i write
String clen = in.readLine(); // read the length
byte[] array = new byte[Integer.parseInt(clen)]; // create the array of that length
dist.readFully(array); // read the array
// i am unable to read the array here at all !
PrivateKey priKey = readKeyFromFileprivate("aliceprivate.txt");
Cipher vote = Cipher.getInstance("RSA");
vote.init(Cipher.DECRYPT_MODE, priKey);
byte[] voteData = vote.doFinal(array);
System.out.println(voteData);
// finally print the decrypted array
I have checked the encryption and decryption process by writing to a file it works properly.
i am using DataInput and DataOutput stream at both ends.
Can you please tell me what is wrong with my code !
Don't mix reading character data and binary data on the same stream (at least, not with different streams). you didn't show the type of "in", but i'm guessing it is a BufferedReader (the key point here being "buffered"). BufferedReader will read more than the next line, so part of your byte[] is sitting in your BufferedReader. use the same DataOutputStream/DataInputStream for all operations on the stream. if you need to write textual data, use writeUTF/readUTF. when you write the length of the byte[], just use writeInt/readInt.