• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ebourg / jsign / #422

04 Aug 2026 09:03AM UTC coverage: 81.859% (+0.5%) from 81.393%
#422

push

ebourg
Marked the Jsign 8.0 preview features in the documentation

6200 of 7574 relevant lines covered (81.86%)

0.82 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.73
/jsign-crypto/src/main/java/net/jsign/CertificateChain.java
1
/*
2
 * Copyright 2026 Emmanuel Bourg
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 net.jsign;
18

19
import java.io.File;
20
import java.io.FileInputStream;
21
import java.io.IOException;
22
import java.io.InputStream;
23
import java.net.URL;
24
import java.security.cert.CertStore;
25
import java.security.cert.CertStoreException;
26
import java.security.cert.Certificate;
27
import java.security.cert.CertificateException;
28
import java.security.cert.CertificateFactory;
29
import java.security.cert.X509CertSelector;
30
import java.security.cert.X509Certificate;
31
import java.util.ArrayList;
32
import java.util.Arrays;
33
import java.util.Collection;
34
import java.util.Collections;
35
import java.util.Comparator;
36
import java.util.HashMap;
37
import java.util.HashSet;
38
import java.util.Iterator;
39
import java.util.LinkedHashSet;
40
import java.util.List;
41
import java.util.Map;
42
import java.util.Set;
43
import java.util.stream.Collectors;
44
import javax.security.auth.x500.X500Principal;
45

46
import org.bouncycastle.asn1.ASN1OctetString;
47
import org.bouncycastle.asn1.x509.AccessDescription;
48
import org.bouncycastle.asn1.x509.AuthorityInformationAccess;
49
import org.bouncycastle.asn1.x509.Extension;
50
import org.bouncycastle.asn1.x509.X509ObjectIdentifiers;
51

52
/**
53
 * Chain of X.509 certificates.
54
 *
55
 * <p>The chain may be incomplete and can be completed by downloading the missing issuer certificates
56
 * from the URLs specified in the Authority Information Access extension of the certificates.</p>
57
 *
58
 * @since 8.0
59
 */
60
public class CertificateChain implements Iterable<X509Certificate> {
61

62
    /** Download links of old certificates not accessible through an AIA field*/
63
    private static final Map<String, String> certurls = new HashMap<>();
1✔
64
    static {
65
        certurls.put("CN=Certum CA, O=Unizeto Sp. z o.o., C=PL", "http://ctldl.windowsupdate.com/msdownload/update/v3/static/trustedr/en/6252dc40f71143a22fde9ef7348e064251b18118.crt");
1✔
66
        certurls.put("CN=GlobalSign, O=GlobalSign, OU=GlobalSign Root CA - R3", "http://ctldl.windowsupdate.com/msdownload/update/v3/static/trustedr/en/d69b561148f01c77c54578c10926df5b856976ad.crt");
1✔
67
        certurls.put("CN=Go Daddy Root Certificate Authority - G2, O=\"GoDaddy.com, Inc.\", L=Scottsdale, ST=Arizona, C=US", "http://ctldl.windowsupdate.com/msdownload/update/v3/static/trustedr/en/47beabc922eae80e78783462a79f45c254fde68b.crt");
1✔
68
        certurls.put("CN=Microsoft Root Authority, OU=Microsoft Corporation, OU=Copyright (c) 1997 Microsoft Corp.", "http://ctldl.windowsupdate.com/msdownload/update/v3/static/trustedr/en/a43489159a520f0d93d032ccaf37e7fe20a8b419.crt");
1✔
69
        certurls.put("CN=Starfield Root Certificate Authority - G2, O=\"Starfield Technologies, Inc.\", L=Scottsdale, ST=Arizona, C=US", "http://ctldl.windowsupdate.com/msdownload/update/v3/static/trustedr/en/b51c067cee2b0c3df855ab2d92f4fe39d4e70f0e.crt");
1✔
70
        certurls.put("CN=Starfield Services Root Certificate Authority, OU=http://certificates.starfieldtech.com/repository/, O=\"Starfield Technologies, Inc.\", L=Scottsdale, ST=Arizona, C=US", "http://ctldl.windowsupdate.com/msdownload/update/v3/static/trustedr/en/5d003860f002ed829deaa41868f788186d62127f.crt");
1✔
71
        certurls.put("CN=thawte Primary Root CA, OU=\"(c) 2006 thawte, Inc. - For authorized use only\", OU=Certification Services Division, O=\"thawte, Inc.\", C=US", "http://ctldl.windowsupdate.com/msdownload/update/v3/static/trustedr/en/91c6d6ee3e8ac86384e548c299295c756c817b81.crt");
1✔
72
        certurls.put("CN=Thawte Timestamping CA, OU=Thawte Certification, O=Thawte, L=Durbanville, ST=Western Cape, C=ZA", "http://ctldl.windowsupdate.com/msdownload/update/v3/static/trustedr/en/be36a4562fb2ee05dbb3d32323adf445084ed656.crt");
1✔
73
        certurls.put("CN=UTN-USERFirst-Object, OU=http://www.usertrust.com, O=The USERTRUST Network, L=Salt Lake City, ST=UT, C=US", "http://ctldl.windowsupdate.com/msdownload/update/v3/static/trustedr/en/e12dfb4b41d7d9c32b30514bac1d81d8385e2d46.crt");
1✔
74
        certurls.put("CN=VeriSign Class 3 Public Primary Certification Authority - G5, OU=\"(c) 2006 VeriSign, Inc. - For authorized use only\", OU=VeriSign Trust Network, O=\"VeriSign, Inc.\", C=US", "http://ctldl.windowsupdate.com/msdownload/update/v3/static/trustedr/en/4eb6d578499b1ccf5f581ead56be3d9b6744a5e5.crt");
1✔
75
        certurls.put("CN=VeriSign Universal Root Certification Authority, OU=\"(c) 2008 VeriSign, Inc. - For authorized use only\", OU=VeriSign Trust Network, O=\"VeriSign, Inc.\", C=US", "http://ctldl.windowsupdate.com/msdownload/update/v3/static/trustedr/en/3679ca35668772304d30a5fb873b0fa77bb70d54.crt");
1✔
76
    }
1✔
77

78
    private List<X509Certificate> chain;
79

80
    public CertificateChain(Collection<X509Certificate> chain) {
1✔
81
        this.chain = new ArrayList<>(chain);
1✔
82
        this.chain.sort(getChainComparator());
1✔
83
    }
1✔
84

85
    public CertificateChain(Certificate[] chain) {
86
        this(Arrays.stream(chain).map(certificate -> (X509Certificate) certificate).collect(Collectors.toList()));
1✔
87
    }
1✔
88

89
    /**
90
     * Loads the certificate chain from the specified PKCS#7 file.
91
     */
92
    public static CertificateChain load(File file) throws IOException, CertificateException {
93
        try (FileInputStream in = new FileInputStream(file)) {
1✔
94
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1✔
95
            return new CertificateChain((Collection<X509Certificate>) certificateFactory.generateCertificates(in));
1✔
96
        }
97
    }
98

99
    /**
100
     * Returns a comparator that sorts the certificates in the chain in the order of the certification path,
101
     * from the end-entity certificate to the root CA.
102
     */
103
    private Comparator<X509Certificate> getChainComparator() {
104
        return Comparator.comparing(X509Certificate::getBasicConstraints)
1✔
105
                .thenComparing(X509Certificate::getNotBefore, Comparator.reverseOrder())
1✔
106
                .thenComparing(X509Certificate::getSubjectX500Principal, Comparator.comparing(X500Principal::getName));
1✔
107
    }
108

109
    /**
110
     * Builds the certificate chain from the specified end-entity certificate and the issuer in the specified store.
111
     *
112
     * @param certificate the end-entity certificate
113
     * @param certStore the store containing the issuer certificates
114
     */
115
    public static CertificateChain build(X509Certificate certificate, CertStore certStore) throws CertStoreException {
116
        LinkedHashSet<X509Certificate> result = new LinkedHashSet<>();
1✔
117
        buildChain(certificate, certStore, result);
1✔
118

119
        CertificateChain chain = new CertificateChain(Collections.emptyList());
1✔
120
        chain.chain = new ArrayList<>(result);
1✔
121
        return chain;
1✔
122
    }
123

124
    private static void buildChain(X509Certificate certificate, CertStore certStore, Set<X509Certificate> result) throws CertStoreException {
125
        if (!result.add(certificate) || CertificateUtils.isSelfSigned(certificate)) {
1✔
126
            return;
1✔
127
        }
128

129
        X509CertSelector selector = new X509CertSelector();
1✔
130
        selector.setSubject(certificate.getIssuerX500Principal());
1✔
131

132
        for (X509Certificate candidate : (Collection<X509Certificate>) certStore.getCertificates(selector)) {
1✔
133
            buildChain(candidate, certStore, result);
1✔
134
        }
1✔
135
    }
1✔
136

137
    /**
138
     * Returns the end-entity certificate of the chain (the first certificate in the list).
139
     */
140
    public X509Certificate getLeaf() {
141
        return chain.get(0);
1✔
142
    }
143

144
    /**
145
     * Returns the certificate chain as an array of certificates. The array is sorted in the order of the certification
146
     * path, from the end-entity certificate to the root CA.
147
     */
148
    public X509Certificate[] toArray() {
149
        return chain.toArray(new X509Certificate[0]);
1✔
150
    }
151

152
    /**
153
     * Returns the certificate chain as a list of certificates. The list is sorted in the order of the certification
154
     * path, from the end-entity certificate to the root CA.
155
     */
156
    public List<X509Certificate> toList() {
157
        return new ArrayList<>(chain);
1✔
158
    }
159

160
    @Override
161
    public Iterator<X509Certificate> iterator() {
162
        return toList().iterator();
1✔
163
    }
164

165
    /**
166
     * Completes the chain with the missing issuer certificates.
167
     */
168
    public CertificateChain complete() {
169
        // find the orphan certificates in the chain (certificates whose issuer is not present in the chain)
170
        Set<String> missingIssuerNames = chain.stream().map(c -> c.getIssuerX500Principal().getName())
1✔
171
                .collect(Collectors.toCollection(LinkedHashSet::new));
1✔
172
        for (X509Certificate certificate : chain) {
1✔
173
            missingIssuerNames.remove(certificate.getSubjectX500Principal().getName());
1✔
174
        }
1✔
175
        Set<X509Certificate> orphanCertificates = new HashSet<>();
1✔
176
        for (X509Certificate certificate : chain) {
1✔
177
            if (missingIssuerNames.contains(certificate.getIssuerX500Principal().getName())) {
1✔
178
                orphanCertificates.add(certificate);
1✔
179
            }
180
        }
1✔
181

182
        List<X509Certificate> fullChain = new ArrayList<>(chain);
1✔
183
        for (X509Certificate orphanCertificate : orphanCertificates) {
1✔
184
            fullChain.remove(orphanCertificate);
1✔
185
            fullChain.addAll(getCertificateChain(orphanCertificate, 10));
1✔
186
        }
1✔
187
        chain = fullChain;
1✔
188

189
        return this;
1✔
190
    }
191

192
    /**
193
     * Returns the authority information access extension of the specified certificate.
194
     */
195
    private static AuthorityInformationAccess getAuthorityInformationAccess(X509Certificate certificate) {
196
        byte[] aia = certificate.getExtensionValue(Extension.authorityInfoAccess.getId());
1✔
197
        return aia != null ? AuthorityInformationAccess.getInstance(ASN1OctetString.getInstance(aia).getOctets()) : null;
1✔
198
    }
199

200
    /**
201
     * Returns the issuer certificate URL of the specified certificate (HTTP only).
202
     */
203
    static String getIssuerCertificateURL(X509Certificate certificate) {
204
        AuthorityInformationAccess aia = getAuthorityInformationAccess(certificate);
1✔
205
        if (aia != null) {
1✔
206
            for (AccessDescription access : aia.getAccessDescriptions()) {
1✔
207
                if (X509ObjectIdentifiers.id_ad_caIssuers.equals(access.getAccessMethod())) {
1✔
208
                    String url = access.getAccessLocation().getName().toString();
1✔
209
                    if (url.startsWith("http")) {
1✔
210
                        return access.getAccessLocation().getName().toString();
1✔
211
                    }
212
                }
213
            }
214
        }
215

216
        return certurls.get(certificate.getIssuerDN().toString());
1✔
217
    }
218

219
    /**
220
     * Returns the issuer certificates of the specified certificate. Multiple issuer certificates may be returned
221
     * if the certificate is cross-signed.
222
     */
223
    private static Collection<X509Certificate> getIssuerCertificates(X509Certificate certificate) throws IOException, CertificateException {
224
        String certificateURL = getIssuerCertificateURL(certificate);
1✔
225
        if (certificateURL != null) {
1✔
226
            File cacheDirectory = new File(OSUtils.getCacheDirectory("jsign"), "certificates");
1✔
227
            HttpClient cache = new HttpClient(cacheDirectory, 90 * 24 * 3600 * 1000L);
1✔
228
            try (InputStream in = cache.getInputStream(new URL(certificateURL))) {
1✔
229
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1✔
230
                return (Collection) certificateFactory.generateCertificates(in);
1✔
231
            }
232
        }
233

234
        return Collections.emptyList();
1✔
235
    }
236

237
    /**
238
     * Returns the certificate chain of the specified certificate up to the specified depth.
239
     */
240
    private static Collection<X509Certificate> getCertificateChain(X509Certificate certificate, int maxDepth) {
241
        List<X509Certificate> chain = new ArrayList<>();
1✔
242
        chain.add(certificate);
1✔
243

244
        if (maxDepth > 0 && !CertificateUtils.isSelfSigned(certificate)) {
1✔
245
            try {
246
                Collection<X509Certificate> issuers = getIssuerCertificates(certificate);
1✔
247
                for (X509Certificate issuer : issuers) {
1✔
248
                    chain.addAll(getCertificateChain(issuer, maxDepth - 1));
1✔
249
                }
1✔
250
            } catch (Exception e) {
×
251
                e.printStackTrace();
×
252
            }
1✔
253
        }
254

255
        return chain;
1✔
256
    }
257
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc