Question

I am trying to read byte[] that is being send from a client to a server.

This is my client code...

 din = new DataInputStream(socket.getInputStream());
 dout = new DataOutputStream(socket.getOutputStream());

 Cipher cipher = Cipher.getInstance("RSA"); 
 // encrypt the aeskey using the public key 
 cipher.init(Cipher.ENCRYPT_MODE, pk);

 byte[] cipherText = cipher.doFinal(aesKey.getEncoded());
 dout.write(cipherText);

And this is my server code...

 DataInputStream dis = new DataInputStream(socket.getInputStream());          
 DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

 String chiper = dis.readUTF();
 System.out.println(chiper);

However, the dis.readUTF(); line fails with an exception...

java.io.EOFException at java.io.DataInputStream.readFully(DataInputStream.java:197)
    at java.io.DataInputStream.readUTF(DataInputStream.java:609)
    at java.io.DataInputStream.readUTF(DataInputStream.java:564)
    at gameserver.ClientHandler.run(GameServer.java:65)

Could someone please help me understand why this doesn't work.

Was it helpful?

Solution

For starters, if you write a sequence of (encrypted!) bytes at one end, and trying to read a UTF-formatted string at the other end...you're going to have a bad time.

I'd suggest that on the client side you should do something like

dout.writeInt(cipherText.length);
dout.write(cipherText);

and then on the server side you should do something like

int byteLength = dis.readInt(); // now I know how many bytes to read
byte[] theBytes = new byte[byteLength];
dis.readFully(theBytes);

OTHER TIPS

DataIputStream.readUTF() is for data that you have written with DataOutputStream.writeUTF()`. You haven't written UTF so you can't read it.

This is binary data so you shouldn't be thinking about UTF or strings at all. Write the length of the array with writeInt(), then the array with write(). At the other end, read the length with readInt(), allocate a byte[] buffer that big and then read the ciphertext into it with readFully().

Yo have to get the message with the read method and get the number of characters of the real messages and then convert this to a string

int bytesRead = 0;
byte[] messageByte = new byte[1000];

bytesRead = dis.read(messageByte);
String chiper = new String(messageByte, 0, bytesRead);
System.out.println(chiper);

on client side, you should convert the byte[] array to String and use dout.writeUTF() to send the converted String.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top