Home | History | Annotate | Download | only in internal
      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 com.squareup.okhttp.internal;
     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 = { certificate };
     73     keyStore.setKeyEntry("private", keyPair.getPrivate(), password, certificateChain);
     74     keyStore.setCertificateEntry("cert", certificate);
     75 
     76     // Wrap it up in an SSL context.
     77     KeyManagerFactory keyManagerFactory =
     78         KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
     79     keyManagerFactory.init(keyStore, password);
     80     TrustManagerFactory trustManagerFactory =
     81         TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
     82     trustManagerFactory.init(keyStore);
     83     SSLContext sslContext = SSLContext.getInstance("TLS");
     84     sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
     85         new SecureRandom());
     86     return sslContext;
     87   }
     88 
     89   private KeyPair generateKeyPair() throws GeneralSecurityException {
     90     KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
     91     keyPairGenerator.initialize(1024, new SecureRandom());
     92     return keyPairGenerator.generateKeyPair();
     93   }
     94 
     95   /**
     96    * Generates a certificate for {@code hostName} containing {@code keyPair}'s
     97    * public key, signed by {@code keyPair}'s private key.
     98    */
     99   @SuppressWarnings("deprecation") // use the old Bouncy Castle APIs to reduce dependencies.
    100   private X509Certificate selfSignedCertificate(KeyPair keyPair) throws GeneralSecurityException {
    101     X509V3CertificateGenerator generator = new X509V3CertificateGenerator();
    102     X500Principal issuer = new X500Principal("CN=" + hostName);
    103     X500Principal subject = new X500Principal("CN=" + hostName);
    104     generator.setSerialNumber(BigInteger.ONE);
    105     generator.setIssuerDN(issuer);
    106     generator.setNotBefore(new Date(notBefore));
    107     generator.setNotAfter(new Date(notAfter));
    108     generator.setSubjectDN(subject);
    109     generator.setPublicKey(keyPair.getPublic());
    110     generator.setSignatureAlgorithm("SHA256WithRSAEncryption");
    111     return generator.generateX509Certificate(keyPair.getPrivate(), "BC");
    112   }
    113 
    114   private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
    115     try {
    116       KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    117       InputStream in = null; // By convention, 'null' creates an empty key store.
    118       keyStore.load(in, password);
    119       return keyStore;
    120     } catch (IOException e) {
    121       throw new AssertionError(e);
    122     }
    123   }
    124 }
    125