-1

我正在编写一个应用程序,我在其中通过 java 中的套接字传输字节数组。

客户端字节数组的生成如下:

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

在服务器端我写

 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

我已经通过写入文件来检查加密和解密过程,它可以正常工作。

我在两端使用 DataInput 和 DataOutput 流。

你能告诉我我的代码有什么问题吗!

4

1 回答 1

2

不要在同一个流上混合读取字符数据和二进制数据(至少,不要使用不同的流)。你没有显示“in”的类型,但我猜它是一个 BufferedReader (这里的关键点是“缓冲”)。BufferedReader 将读取下一行更多的内容,因此您的 byte[] 的一部分位于您的 BufferedReader 中。对流上的所有操作使用相同的 DataOutputStream/DataInputStream。如果您需要写入文本数据,请使用 writeUTF/readUTF。当您写入 byte[] 的长度时,只需使用 writeInt/readInt。

于 2012-05-01T20:27:08.290 回答