Home | History | Annotate | Download | only in ssl
      1 /*
      2  * Copyright (C) 2012 Square, Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package libcore.net.ssl;
     18 
     19 import java.io.IOException;
     20 import java.io.InputStream;
     21 import java.math.BigInteger;
     22 import java.security.GeneralSecurityException;
     23 import java.security.KeyPair;
     24 import java.security.KeyPairGenerator;
     25 import java.security.KeyStore;
     26 import java.security.SecureRandom;
     27 import java.security.Security;
     28 import java.security.cert.Certificate;
     29 import java.security.cert.X509Certificate;
     30 import java.util.Date;
     31 import javax.net.ssl.KeyManagerFactory;
     32 import javax.net.ssl.SSLContext;
     33 import javax.net.ssl.TrustManagerFactory;
     34 import javax.security.auth.x500.X500Principal;
     35 import org.bouncycastle.jce.provider.BouncyCastleProvider;
     36 import org.bouncycastle.x509.X509V3CertificateGenerator;
     37 
     38 /**
     39  * Constructs an SSL context for testing. This uses Bouncy Castle to generate a
     40  * self-signed certificate for a single hostname such as "localhost".
     41  *
     42  * <p>The crypto performed by this class is relatively slow. Clients should
     43  * reuse SSL context instances where possible.
     44  */
     45 public final class SslContextBuilder {
     46     static {
     47         Security.addProvider(new BouncyCastleProvider());
     48     }
     49 
     50     private static final long ONE_DAY_MILLIS = 1000L * 60 * 60 * 24;
     51     private final String hostName;
     52     private long notBefore = System.currentTimeMillis();
     53     private long notAfter = System.currentTimeMillis() + ONE_DAY_MILLIS;
     54 
     55     /**
     56      * @param hostName the subject of the host. For TLS this should be the
     57      *     domain name that the client uses to identify the server.
     58      */
     59     public SslContextBuilder(String hostName) {
     60         this.hostName = hostName;
     61     }
     62 
     63     public SSLContext build() throws GeneralSecurityException {
     64         char[] password = "password".toCharArray();
     65 
     66         // Generate public and private keys and use them to make a self-signed certificate.
     67         KeyPair keyPair = generateKeyPair();
     68         X509Certificate certificate = selfSignedCertificate(keyPair);
     69 
     70         // Put 'em in a key store.
     71         KeyStore keyStore = newEmptyKeyStore(password);
     72         Certificate[] certificateChain = {
     73                 certificate
     74         };
     75         keyStore.setKeyEntry("private", keyPair.getPrivate(), password, certificateChain);
     76         keyStore.setCertificateEntry("cert", certificate);
     77 
     78         // Wrap it up in an SSL context.
     79         KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
     80                 KeyManagerFactory.getDefaultAlgorithm());
     81         keyManagerFactory.init(keyStore, password);
     82         TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
     83                 TrustManagerFactory.getDefaultAlgorithm());
     84         trustManagerFactory.init(keyStore);
     85         SSLContext sslContext = SSLContext.getInstance("TLS");
     86         sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
     87                 new SecureRandom());
     88         return sslContext;
     89     }
     90 
     91     private KeyPair generateKeyPair() throws GeneralSecurityException {
     92         KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
     93         keyPairGenerator.initialize(1024, new SecureRandom());
     94         return keyPairGenerator.generateKeyPair();
     95     }
     96 
     97     /**
     98      * Generates a certificate for {@code hostName} containing {@code keyPair}'s
     99      * public key, signed by {@code keyPair}'s private key.
    100      */
    101     @SuppressWarnings("deprecation") // use the old Bouncy Castle APIs to reduce dependencies.
    102     private X509Certificate selfSignedCertificate(KeyPair keyPair) throws GeneralSecurityException {
    103         X509V3CertificateGenerator generator = new X509V3CertificateGenerator();
    104         X500Principal issuer = new X500Principal("CN=" + hostName);
    105         X500Principal subject = new X500Principal("CN=" + hostName);
    106         generator.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    107         generator.setIssuerDN(issuer);
    108         generator.setNotBefore(new Date(notBefore));
    109         generator.setNotAfter(new Date(notAfter));
    110         generator.setSubjectDN(subject);
    111         generator.setPublicKey(keyPair.getPublic());
    112         generator.setSignatureAlgorithm("SHA256WithRSAEncryption");
    113         return generator.generateX509Certificate(keyPair.getPrivate(), "BC");
    114     }
    115 
    116     private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
    117         try {
    118             KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    119             InputStream in = null; // By convention, 'null' creates an empty key store.
    120             keyStore.load(in, password);
    121             return keyStore;
    122         } catch (IOException e) {
    123             throw new AssertionError(e);
    124         }
    125     }
    126 }
    127