1/*
2 * Copyright (C) 2012 The Android Open Source Project
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
17package org.conscrypt;
18
19import java.security.cert.CertificateException;
20import java.security.cert.X509Certificate;
21import java.security.interfaces.RSAPublicKey;
22
23public final class ChainStrengthAnalyzer {
24
25    private static final int MIN_MODULUS = 1024;
26    private static final String[] OID_BLACKLIST = {"1.2.840.113549.1.1.4"}; // MD5withRSA
27
28    public static final void check(X509Certificate[] chain) throws CertificateException {
29        for (X509Certificate cert : chain) {
30            checkCert(cert);
31        }
32    }
33
34    private static final void checkCert(X509Certificate cert) throws CertificateException {
35        checkModulusLength(cert);
36        checkNotMD5(cert);
37    }
38
39    private static final void checkModulusLength(X509Certificate cert) throws CertificateException {
40        Object pubkey = cert.getPublicKey();
41        if (pubkey instanceof RSAPublicKey) {
42            int modulusLength = ((RSAPublicKey) pubkey).getModulus().bitLength();
43            if(!(modulusLength >= MIN_MODULUS)) {
44                throw new CertificateException("Modulus is < 1024 bits");
45            }
46        }
47    }
48
49    private static final void checkNotMD5(X509Certificate cert) throws CertificateException {
50        String oid = cert.getSigAlgOID();
51        for (String blacklisted : OID_BLACKLIST) {
52            if (oid.equals(blacklisted)) {
53                throw new CertificateException("Signature uses an insecure hash function");
54            }
55        }
56    }
57}
58
59