views:

30

answers:

2

Hi, 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,

Server code:

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

Client code

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

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 length more than 4 bytes: 111 at org.bouncycastle.jce.provider.JDKX509CertificateFactory.engineGenerateCertificate(Unknown Source) at java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:322)

and this is the line from which it comes from

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

Anyone can help me?

Thanks in advance

+1  A: 

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

EJP
A: 

It looks possible that your problem might be due to using a PrintWriter to send, and possibly something different to read (scanner). You could try using a StringWriter and StringReader to have a match at either end and then also you can debug if what you send is a perfect match for what you receive.

jowierun