FileDocCategorySizeDatePackage
SSLSocketFactory.javaAPI DocAndroid 1.5 API14230Wed May 06 22:41:10 BST 2009org.apache.http.conn.ssl

SSLSocketFactory

public class SSLSocketFactory extends Object implements LayeredSocketFactory
Layered socket factory for TLS/SSL connections, based on JSSE. .

SSLSocketFactory can be used to validate the identity of the HTTPS server against a list of trusted certificates and to authenticate to the HTTPS server using a private key.

SSLSocketFactory will enable server authentication when supplied with a {@link KeyStore truststore} file containg one or several trusted certificates. The client secure socket will reject the connection during the SSL session handshake if the target HTTPS server attempts to authenticate itself with a non-trusted certificate.

Use JDK keytool utility to import a trusted certificate and generate a truststore file:

keytool -import -alias "my server cert" -file server.crt -keystore my.truststore

SSLSocketFactory will enable client authentication when supplied with a {@link KeyStore keystore} file containg a private key/public certificate pair. The client secure socket will use the private key to authenticate itself to the target HTTPS server during the SSL session handshake if requested to do so by the server. The target HTTPS server will in its turn verify the certificate presented by the client in order to establish client's authenticity

Use the following sequence of actions to generate a keystore file

  • Use JDK keytool utility to generate a new key

    keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore
    For simplicity use the same password for the key as that of the keystore

  • Issue a certificate signing request (CSR)

    keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore

  • Send the certificate request to the trusted Certificate Authority for signature. One may choose to act as her own CA and sign the certificate request using a PKI tool, such as OpenSSL.

  • Import the trusted CA root certificate

    keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore

  • Import the PKCS#7 file containg the complete certificate chain

    keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore

  • Verify the content the resultant keystore file

    keytool -list -v -keystore my.keystore

author
Oleg Kalnichevski
author
Julius Davies

Fields Summary
public static final String
TLS
public static final String
SSL
public static final String
SSLV2
public static final X509HostnameVerifier
ALLOW_ALL_HOSTNAME_VERIFIER
public static final X509HostnameVerifier
BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
public static final X509HostnameVerifier
STRICT_HOSTNAME_VERIFIER
private static final SSLSocketFactory
DEFAULT_FACTORY
The factory using the default JVM settings for secure connections.
private final SSLContext
sslcontext
private final SSLSocketFactory
socketfactory
private final HostNameResolver
nameResolver
private X509HostnameVerifier
hostnameVerifier
Constructors Summary
public SSLSocketFactory(String algorithm, KeyStore keystore, String keystorePassword, KeyStore truststore, SecureRandom random, HostNameResolver nameResolver)


     
          
           
           
          
          
           
            
    
        super();
        if (algorithm == null) {
            algorithm = TLS;
        }
        KeyManager[] keymanagers = null;
        if (keystore != null) {
            keymanagers = createKeyManagers(keystore, keystorePassword);
        }
        TrustManager[] trustmanagers = null;
        if (truststore != null) {
            trustmanagers = createTrustManagers(truststore);
        }
        this.sslcontext = SSLContext.getInstance(algorithm);
        this.sslcontext.init(keymanagers, trustmanagers, random);
        this.socketfactory = this.sslcontext.getSocketFactory();
        this.nameResolver = nameResolver;
    
public SSLSocketFactory(KeyStore keystore, String keystorePassword, KeyStore truststore)

        this(TLS, keystore, keystorePassword, truststore, null, null);
    
public SSLSocketFactory(KeyStore keystore, String keystorePassword)

        this(TLS, keystore, keystorePassword, null, null, null);
    
public SSLSocketFactory(KeyStore truststore)

        this(TLS, null, null, truststore, null, null);
    
public SSLSocketFactory(SSLSocketFactory socketfactory)
Constructs an HttpClient SSLSocketFactory backed by the given JSSE SSLSocketFactory.

hide

        super();
        this.sslcontext = null;
        this.socketfactory = socketfactory;
        this.nameResolver = null;
    
private SSLSocketFactory()
Creates the default SSL socket factory. This constructor is used exclusively to instantiate the factory for {@link #getSocketFactory getSocketFactory}.

        super();
        this.sslcontext = null;
        this.socketfactory = HttpsURLConnection.getDefaultSSLSocketFactory();
        this.nameResolver = null;
    
Methods Summary
public java.net.SocketconnectSocket(java.net.Socket sock, java.lang.String host, int port, java.net.InetAddress localAddress, int localPort, org.apache.http.params.HttpParams params)


        if (host == null) {
            throw new IllegalArgumentException("Target host may not be null.");
        }
        if (params == null) {
            throw new IllegalArgumentException("Parameters may not be null.");
        }

        SSLSocket sslsock = (SSLSocket)
            ((sock != null) ? sock : createSocket());

        if ((localAddress != null) || (localPort > 0)) {

            // we need to bind explicitly
            if (localPort < 0)
                localPort = 0; // indicates "any"

            InetSocketAddress isa =
                new InetSocketAddress(localAddress, localPort);
            sslsock.bind(isa);
        }

        int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
        int soTimeout = HttpConnectionParams.getSoTimeout(params);

        InetSocketAddress remoteAddress;
        if (this.nameResolver != null) {
            remoteAddress = new InetSocketAddress(this.nameResolver.resolve(host), port); 
        } else {
            remoteAddress = new InetSocketAddress(host, port);            
        }
        
        sslsock.connect(remoteAddress, connTimeout);

        sslsock.setSoTimeout(soTimeout);
        try {
            hostnameVerifier.verify(host, sslsock);
            // verifyHostName() didn't blowup - good!
        } catch (IOException iox) {
            // close the socket before re-throwing the exception
            try { sslsock.close(); } catch (Exception x) { /*ignore*/ }
            throw iox;
        }

        return sslsock;
    
private static javax.net.ssl.KeyManager[]createKeyManagers(java.security.KeyStore keystore, java.lang.String password)

        if (keystore == null) {
            throw new IllegalArgumentException("Keystore may not be null");
        }
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, password != null ? password.toCharArray(): null);
        return kmfactory.getKeyManagers(); 
    
public java.net.SocketcreateSocket()


        // the cast makes sure that the factory is working as expected
        return (SSLSocket) this.socketfactory.createSocket();
    
public java.net.SocketcreateSocket(java.net.Socket socket, java.lang.String host, int port, boolean autoClose)

        SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(
              socket,
              host,
              port,
              autoClose
        );
        hostnameVerifier.verify(host, sslSocket);
        // verifyHostName() didn't blowup - good!
        return sslSocket;
    
private static javax.net.ssl.TrustManager[]createTrustManagers(java.security.KeyStore keystore)

 
        if (keystore == null) {
            throw new IllegalArgumentException("Keystore may not be null");
        }
        TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm());
        tmfactory.init(keystore);
        return tmfactory.getTrustManagers();
    
public org.apache.http.conn.ssl.X509HostnameVerifiergetHostnameVerifier()

        return hostnameVerifier;
    
public static org.apache.http.conn.ssl.SSLSocketFactorygetSocketFactory()
Gets an singleton instance of the SSLProtocolSocketFactory.

return
a SSLProtocolSocketFactory

    
                   
        
        return DEFAULT_FACTORY;
    
public booleanisSecure(java.net.Socket sock)
Checks whether a socket connection is secure. This factory creates TLS/SSL socket connections which, by default, are considered secure.
Derived classes may override this method to perform runtime checks, for example based on the cypher suite.

param
sock the connected socket
return
true
throws
IllegalArgumentException if the argument is invalid


        if (sock == null) {
            throw new IllegalArgumentException("Socket may not be null.");
        }
        // This instanceof check is in line with createSocket() above.
        if (!(sock instanceof SSLSocket)) {
            throw new IllegalArgumentException
                ("Socket not created by this factory.");
        }
        // This check is performed last since it calls the argument object.
        if (sock.isClosed()) {
            throw new IllegalArgumentException("Socket is closed.");
        }

        return true;

    
public voidsetHostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier hostnameVerifier)

        if ( hostnameVerifier == null ) {
            throw new IllegalArgumentException("Hostname verifier may not be null");
        }
        this.hostnameVerifier = hostnameVerifier;