Home | History | Annotate | Download | only in tls
      1 /*
      2  * Copyright (C) 2016 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 package com.squareup.okhttp.internal.tls;
     17 
     18 import java.security.PublicKey;
     19 import java.security.cert.X509Certificate;
     20 import java.util.ArrayList;
     21 import java.util.LinkedHashMap;
     22 import java.util.List;
     23 import java.util.Map;
     24 import javax.security.auth.x500.X500Principal;
     25 
     26 public final class RealTrustRootIndex implements TrustRootIndex {
     27   private final Map<X500Principal, List<X509Certificate>> subjectToCaCerts;
     28 
     29   public RealTrustRootIndex(X509Certificate... caCerts) {
     30     subjectToCaCerts = new LinkedHashMap<>();
     31     for (X509Certificate caCert : caCerts) {
     32       X500Principal subject = caCert.getSubjectX500Principal();
     33       List<X509Certificate> subjectCaCerts = subjectToCaCerts.get(subject);
     34       if (subjectCaCerts == null) {
     35         subjectCaCerts = new ArrayList<>(1);
     36         subjectToCaCerts.put(subject, subjectCaCerts);
     37       }
     38       subjectCaCerts.add(caCert);
     39     }
     40   }
     41 
     42   @Override public X509Certificate findByIssuerAndSignature(X509Certificate cert) {
     43     X500Principal issuer = cert.getIssuerX500Principal();
     44     List<X509Certificate> subjectCaCerts = subjectToCaCerts.get(issuer);
     45     if (subjectCaCerts == null) return null;
     46 
     47     for (X509Certificate caCert : subjectCaCerts) {
     48       PublicKey publicKey = caCert.getPublicKey();
     49       try {
     50         cert.verify(publicKey);
     51         return caCert;
     52       } catch (Exception ignored) {
     53       }
     54     }
     55 
     56     return null;
     57   }
     58 }
     59