SSL Socket connection

前端 未结 1 1673
走了就别回头了
走了就别回头了 2020-12-08 05:23

How can I create a SSL Socket connection?

I realy need to create a keystore? This keystore should be shared with all my client applications?

I have create a

相关标签:
1条回答
  • 2020-12-08 05:58

    You need a certificate to establish an ssl connection, you can load the certificate inside a keystore or you can load the certificate itself. I will show some examples for the keystore option.

    Your code needs some parameters to run :

    java -Djavax.net.ssl.keyStore=keyStoreFile -Djavax.net.ssl.keyStorePassword=keystorePassword Server
    

    You can also load the keystore with java code , the simplest solution for this is to set the system properties:

    System.setProperty("javax.net.ssl.keyStore", 'keystoreFile');
    System.setProperty("javax.net.ssl.keyStorePassword", 'keystorePassword ');
    

    Also you can load the keystore with a different way, its more complicated but you have the ability to do more complex things :

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream("keystoreFile"), "keystorePassword".toCharArray());
    
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    kmf.init(ks, "keystorePassword".toCharArray());
    
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); 
    tmf.init(ks);
    
    SSLContext sc = SSLContext.getInstance("TLS"); 
    TrustManager[] trustManagers = tmf.getTrustManagers(); 
    sc.init(kmf.getKeyManagers(), trustManagers, null); 
    
    SSLServerSocketFactory ssf = sc.getServerSocketFactory(); 
    SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(serverport);
    SSLSocket c = (SSLSocket) s.accept();
    

    For the clients there are a few changes in the code last lines, the 3 last lines will be replaced with these :

    SSLSocketFactory ssf = sc.getSocketFactory(); 
    SSLSocket s = (SSLSocket) ssf.createSocket(serverip, serverport);
    s.startHandshake();
    

    If you want to load a keystore for android the type will have to be "BKS" and not "JKS". You can find easily resources for creating a keystore.

    0 讨论(0)
提交回复
热议问题