0

我需要使用套接字将 v3certificate 从服务器发送到客户端。为此:服务器端,我生成一个使用 base64.encode 编码的证书,然后将其发送给客户端。客户端,我收到包含证书的字符串,

服务器代码:

 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);

任何人都可以帮助我吗?

提前致谢

4

3 回答 3

2

把它全部扔掉并使用 SSL,它已经完成了所有这些。

于 2010-08-03T02:06:25.060 回答
1

您可以通过字节流通过套接字发送证书:

在配置套接字后的发送方:

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

在配置套接字后的接收方:

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

现在你可以使用这个证书了。例如检索公钥:

PublicKey thepublicKey = jsCert.getPublicKey();
于 2014-01-18T09:52:56.010 回答
0

看起来您的问题可能是由于使用 PrintWriter 发送,并且可能是读取不同的东西(扫描仪)。您可以尝试使用 StringWriter 和 StringReader 在任一端进行匹配,然后您也可以调试您发送的内容是否与您收到的内容完美匹配。

于 2010-08-03T02:52:19.203 回答