How to specify the ciphersuite to be used in SSL s

2019-01-26 05:51发布

I have created a socket on port 443 as in the following line:

socket = (SSLSocket) factory.createSocket(hostName, port);

Then, I wanted to see the enabled ciphersuites in this socket, I used:

String[] enCiphersuite=socket.getEnabledCipherSuites();
System.out.println("Enabled ciphersuites are: "+Arrays.toString(enCiphersuite));

Then, I want to pick only one ciphersuite that I want my application to use when creating handshake with the remote server. I did the following:

String pickedCipher[] ={"TLS_RSA_WITH_AES_128_CBC_SHA"}; 
socket.setEnabledCipherSuites(pickedCipher);
System.out.println("ciphersuite set to: "+Arrays.toString(pickedCipher));

Then I made the handshake, and checked the session ciphersuite:

socket.startHandshake();
System.out.println("Session ciphersuite is"+socket.getSession().getCipherSuite() );

But I found that the name of the cipher printed in the previous printout statement after the handshake (as I understand, this is the actually used cipher in the session) is not what I set earlier using setEnabledCipherSuites()

Why am I still not see my chosen ciphersuite is the used one ? and also, I also tried to getEnabledCipherSuites() and print it out after I setEnabledCipherSuites and found the list has not changed to what I have set. I am not sure when I print the enabled ciphersuite, is this list of ciphersuites depends on Java and always the same list, or depends on the client or on the server? Can any body explain ?

EDIT: Before the handshake I only have the following lines:

SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory(); 
SSLSocket socket=null;
try {
socket = (SSLSocket) factory.createSocket(hostName, port);
socket.setSoTimeout(15000); 
socket.startHandshake(); //handshake
.
.

1条回答
萌系小妹纸
2楼-- · 2019-01-26 06:18

I found out that I added socket.getsession() before the setEnableCipherSuite() in order to print out the enabled cipheres before setting them. When I removed it, the cipher has been set. why is that ?

As documented in the SSLSocket JavaDoc:

The initial handshake on this connection can be initiated in one of three ways:

  • calling startHandshake which explicitly begins handshakes, or
  • any attempt to read or write application data on this socket causes an implicit handshake, or
  • a call to getSession tries to set up a session if there is no currently valid session, and an implicit handshake is done.

If you call getSession() before calling setEnabledCipherSuite(), the handshake has already been done when you try to set the enabled cipher suites, so this session's cipher suite has already been selected.

查看更多
登录 后发表回答