Java: how to add SSL client authentication

I have this code to connect the server and the client using SSL. Now I want to add client authentication:

(I have a server keystore (jceks type) and a client keystore (JKS type). The server uses a truststore (cacerts), in which I imported two certificates, because I also want to use this truststore for client authentication)

Client code:

System.setProperty("javax.net.ssl.trustStore",cerServer);
System.setProperty("javax.net.ssl.trustStoreType","JCEKS");
System.setProperty("javax.net.ssl.trustStorePassword",pwdCacerts);

SSLSocketFactory sslsocketfactory = (SSLSocketFactory)  SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("localhost",port);

Server code:

KeyStore ks = LoadKeyStore(new File(serverKeyStore),pwdKeyStore,"JCEKS");
KeyManagerFactory kmf; 
kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks,pwdKeyStore.tocharArray());

SSLContext sc = SSLContext.getInstance("SSL");
sc.init(kmf.getKeyManagers(),null,null);   

SSLServerSocketFactory ssf = sc.getServerSocketFactory(); 
sslserversocket = (SSLServerSocket) ssf.createServerSocket(port);

Thank you in advance for any help

Edit: I add this code on the server side:

System.setProperty("javax.net.ssl.trustStore",cacerts);
System.setProperty("javax.net.ssl.trustStoreType","JKS");
System.setProperty("javax.net.ssl.trustStorePassword",pwdCacerts);

However, if I delete the client certificate in cacerts, the connection will not give me an error, so I think it is wrong to do so

Solution

If you want the system to use client certificate authentication, you need to

>The server requests (or requires) a client certificate This can be done by setting setwantclientauth (true) on the server socket (or setneedclientauth) You also need the server to announce the accepted CAS, which is usually done by using the trust store on the server containing the CA of the client certificate chain (this seems to be javax. Net. SSL. Truststore * on the server you set up). > To configure the client's keystore, which contains the client certificate (if there is an intermediate Ca, it may be linked) and its private key This can be done by setting javax net. ssl. Keystore * (may affect other connections) or use keymanagerfactory to complete it in the same way as on the server side

If you use setwantclientauth (true), you may still not be able to get the error because the server will accept a connection without a client certificate (the server will check the peer certificate of sslsession to see if there is a certificate) Setneedclientauth (true) will disconnect when the client does not provide a certificate

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>