我需要使用套接字将服务器的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);
任何人都可以帮助我行?
在此先感谢
您对字符串的使用是完全错误的。证书是字节数组,字节数组不能正确存储在字符串中。 – 2010-08-03 02:26:12