Java - 通过套接字发送证书 [英] Java - Sending certificate through socket

查看:426
本文介绍了Java - 通过套接字发送证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i need to send a v3certificate from the server to the client using socket. To do this: server side, i generate a certificate which i encode with base64.encode , then i send it to the client. Client side, i receive the string which contain the certificate,

服务器代码:

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

几乎一切正常,在客户端如果我打印字符串i receive i获取包含额外字符和证书数据的文本。但它给我一个错误,当创建证书,客户端。
这是错误:

Almost everything works, in the client side if i print the string i receive i get a text which contain extra character and the certificate data. But it gives me an error when creating the certificate, client side. This is the error:

java.security.cert.CertificateException:java.io.IOException:DER长度超过4个字节:111
at org.bouncycastle.jce.provider.JDKX509CertificateFactory.engineGenerateCertificate(未知源)
at java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:322)

这是它来自的行。

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

任何人都可以帮助我?

推荐答案

将这一切都废弃,并使用已经执行所有操作的SSL。

Throw it all away and use SSL, which already does all that.

这篇关于Java - 通过套接字发送证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆