2010-08-02 172 views
0

我需要使用套接字將服務器的v3certificate發送到客戶端。 要這樣做: 服務器端,我生成一個證書,我用base64.encode編碼,然後我發送給客戶端。 客戶端,我收到包含證書的字符串,Java - 通過套接字發送證書

Server代碼:

X509Certificate certificate = ...; 
sendAnswer(new String(certificate.getEncoded())); 

public static void sendAnswer(String ans) { 
    try { 
     s.shutdownInput(); 
     PrintWriter output = new PrintWriter(s.getOutputStream(), true); 
     output.println(new String(Base64.encode(ans.getBytes()))); 
     output.close(); 

    } catch (IOException ex) { 
     Logger.getLogger(serverThread.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

客戶端代碼

String value = sendMessage(..);//method which receive the certificate from the server 

InputStream inStream = null; 
X509Certificate cert=null; 
inStream = new ByteArrayInputStream(value.getBytes()); 
CertificateFactory cf = CertificateFactory.getInstance("X.509","BC"); 
cert = (X509Certificate)cf.generateCertificate(inStream); 

public static String sendMessage(String url, int port, String tag, byte[] mex1) { 

    Socket link; 
    String reply = ""; 

    byte[] replyDec = null; 

     link = new Socket(InetAddress.getByName(url), port); 
     InputStream i = null; 
     try { 
      i = link.getInputStream(); 
     } catch (IOException ex) { 
      Logger.getLogger(ClientApp.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     Scanner input = new Scanner(i); 

     while (input.hasNextLine()) { 
      reply += input.nextLine(); 
     } 
     replyDec = Base64.decode(reply); 
     input.close(); 
     link.close(); 


    return new String(replyDec); 
} 

幾乎所有的功能,在客戶端,如果我打印字符串我收到我收到一個包含額外字符和證書數據的文本。但是在創建證書時,它給我一個錯誤,客戶端。 這是錯誤:

java.security.cert.CertificateException: java.io.IOException: DER length more than 4 bytes: 111 at org.bouncycastle.jce.provider.JDKX509CertificateFactory.engineGenerateCertificate(Unknown Source) at java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:322)

,這是從它來自

cert = (X509Certificate) cf.generateCertificate(inStream); 

任何人都可以幫助我行?

在此先感謝

+0

您對字符串的使用是完全錯誤的。證書是字節數組,字節數組不能正確存儲在字符串中。 – 2010-08-03 02:26:12

回答

2

把它全部帶走,並使用SSL,它已經做了這一切。

0

看起來你的問題可能是由於使用PrintWriter發送的,並且可能與讀取(掃描儀)有所不同。您可以嘗試使用StringWriter和StringReader在任一端進行匹配,然後您可以調試,如果您發送的內容與您收到的內容完美匹配。

1

可以通過插座的字節流發送證書:

在發送器側插座的配置之後:

ObjectInputStream fromClient; 
fromClient = new ObjectInputStream(socket.getInputStream()); 
byte[] cert = fromClient.readObject(); 
java.security.cert.Certificate jsCert = CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(cert)); 

ObjectOutputStream toServer; 
toServer = new ObjectOutputStream(socket.getOutputStream()); 
byte[] frame = theCertificate.getEncoded(); 
toServer.writeObject(frame); 

插座的配置之後在接收機側現在你可以使用這個證書。例如檢索公鑰:

PublicKey thepublicKey = jsCert.getPublicKey();