客户端未收到加密后截断的数据

时间:2016-01-05 11:19:16

标签: java sockets tcp rsa

将数据发送到服务器的代码

BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
OutputStream ostream = sock.getOutputStream(); 
 PrintWriter pwrite = new PrintWriter(ostream, true);
 // receiving from server ( receiveRead  object)
 InputStream istream = sock.getInputStream();
 BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

 String receiveMessage, sendMessage;               
 while(true)
 {
    sendMessage = keyRead.readLine();  // keyboard reading
    String enc = crypt.encrypt(sendMessage, serverPublicKey);
    System.out.println("sending to server: "+enc);
    pwrite.println(enc);       // sending to server
    pwrite.flush();                    // flush the data
    if((receiveMessage = receiveRead.readLine()) != null) //receive from server
    {
        //System.out.println(crypt.decrypt(receiveMessage, clientPrivateKey)); // displaying at DOS prompt
        System.out.println(receiveMessage);
    }         
  }
加密后的

输出如下所示在控制台上

sending to server: YRJ7ZNgqSQ56nGc8ff7ktoybYEohQJS2R+Vh3YN1YfHipUS64MyFrrYAzL4CiTPv2WF7zvaJst1A
qsiPsv3/1Q==

在服务器上接收的代码

      BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
      // sending to client (pwrite object)
      OutputStream ostream = sock.getOutputStream(); 
      PrintWriter pwrite = new PrintWriter(ostream, true);

      // receiving from server ( receiveRead  object)
      InputStream istream = sock.getInputStream();
      BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

      String receiveMessage, sendMessage;               
      while(true)
      {
        if((receiveMessage = receiveRead.readLine()) != null)  
        {
           //System.out.println(crypt.decrypt(receiveMessage, serverPrivateKey));
            System.out.println(receiveMessage);
        }         
        sendMessage = keyRead.readLine(); 
        String enc = crypt.encrypt(sendMessage, clientPublicKey);
        System.out.println("sending to clinet: "+enc);
        pwrite.println(enc);             
        pwrite.flush();
      }  

但收到数据

YRJ7ZNgqSQ56nGc8ff7ktoybYEohQJS2R+Vh3YN1YfHipUS64MyFrrYAzL4CiTPv2WF7zvaJst1A

的其余部分
qsiPsv3/1Q==
当我从服务器发送内容到客户端时收到

,请帮我找到问题,因为截断的数据解密失败

1 个答案:

答案 0 :(得分:2)

您不仅要加密输入,还要对加密的字节进行Base64编码。您的Base64编码器每隔76个字符插入换行符,这是Base64 transfer encoding for MIME (RFC 2045)的标准。这就是为什么在服务器端,readLine()只能读取前76个字符。

您需要将Base64编码器配置为不添加换行符。