在SSL Socket上进行通信的Android客户端和Java服务器

时间:2014-05-19 10:38:34

标签: java android ssl tcp ssl-certificate

服务器实施

    SSLContext context = SSLContext.getInstance("SSL");
    KeyManagerFactory kmf =  
    KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore ks = KeyStore.getInstance("JKS");
    char[] password = "daniere".toCharArray();
    ks.load(new FileInputStream("C:/Program Files/Java/jre7/bin/keystore.jks"),password);
    kmf.init(ks,password);
    context.init(kmf.getKeyManagers(), null, null);
    SSLServerSocketFactory factory = context.getServerSocketFactory();
    SSLServerSocket server = (SSLServerSocket)factory.createServerSocket(1000);
    System.out.println("Server ready for conncetions...");
    while (true)
    {
     SSLSocket soc = (SSLSocket) server.accept();
    BufferedReader key = new BufferedReader(new InputStreamReader(soc.getInputStream()));

    String c = null;
        while((c=key.readLine())!=null)
        {
            System.out.println(c);
            break;
        }

       }

客户实施

    SSLContext sslcontext = SSLContext.getInstance("SSL");
    KeyStore ks = KeyStore.getInstance("BKS");
    TrustManagerFactory trustManagerFactory =  TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    InputStream in = getClass().getResourceAsStream("/assets/trust.bks");
    ks.load(in,"daniere".toCharArray());
    trustManagerFactory.init(ks);
    sslcontext.init(null, trustManagerFactory.getTrustManagers(), null);
    SSLSocketFactory sf = sslcontext.getSocketFactory();
    SSLSocket s1 = (SSLSocket) sf.createSocket("10.0.0.1", 1000);
    String key = "sdsdsd";
    PrintWriter sockey = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s1.getOutputStream())), true);
    sockey.println(key);
    s1.close;

我有自己创建的证书,密钥库是信任库。 Android客户端只需要验证是否与正确的服务器通信。客户端无需向服务器进行身份验证。

错误

服务器已准备就绪......

服务器连接到:/10.0.0.2:45120 /10.0.0.1:1000

javax.net.ssl.SSLHandshakeException:握手期间远程主机关闭连接     at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)     at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)     at sun.security.ssl.SSLSocketImpl.readDataRecord(未知来源)     at sun.security.ssl.AppInputStream.read(Unknown Source)     at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)     at sun.nio.cs.StreamDecoder.implRead(Unknown Source)     at sun.nio.cs.StreamDecoder.read(Unknown Source)     在java.io.InputStreamReader.read(未知来源)     在java.io.BufferedReader.fill(未知来源)     在java.io.BufferedReader.readLine(未知来源)     在java.io.BufferedReader.readLine(未知来源)     在SSL.SSLserverThread.run(SSLserverThread.java:75) 引起:java.io.EOFException:SSL对等关闭不正确     at sun.security.ssl.InputRecord.read(Unknown Source)     ......还有12个

我无法弄清楚客户端在握手时关闭套接字的原因????? 我花了很多时间在没有运气的情况下搜索这个问题。我是新手,所以

任何帮助表示感谢。

我在纯java上尝试过这个服务器/客户端ssl套接字并且它完美地工作了.. 当尝试在Android上实现作为客户端没有成功。 非常感谢。

0 个答案:

没有答案