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

ebourg / jsign / #386

24 Oct 2025 09:55AM UTC coverage: 80.64% (-2.4%) from 83.057%
#386

push

ebourg
CI build with Java 25

4965 of 6157 relevant lines covered (80.64%)

0.81 hits per line

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

89.57
/jsign-core/src/main/java/net/jsign/SignerHelper.java
1
/*
2
 * Copyright 2017 Emmanuel Bourg and contributors
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.FileWriter;
21
import java.io.IOException;
22
import java.net.Authenticator;
23
import java.net.InetSocketAddress;
24
import java.net.MalformedURLException;
25
import java.net.PasswordAuthentication;
26
import java.net.Proxy;
27
import java.net.ProxySelector;
28
import java.net.SocketAddress;
29
import java.net.URI;
30
import java.net.URL;
31
import java.nio.charset.Charset;
32
import java.nio.file.Files;
33
import java.security.KeyStore;
34
import java.security.KeyStoreException;
35
import java.security.PrivateKey;
36
import java.security.Provider;
37
import java.security.cert.Certificate;
38
import java.util.ArrayList;
39
import java.util.Base64;
40
import java.util.Collection;
41
import java.util.Collections;
42
import java.util.Date;
43
import java.util.LinkedHashSet;
44
import java.util.List;
45
import java.util.Set;
46
import java.util.logging.Logger;
47

48
import org.bouncycastle.asn1.ASN1Encodable;
49
import org.bouncycastle.asn1.ASN1InputStream;
50
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
51
import org.bouncycastle.asn1.DEROctetString;
52
import org.bouncycastle.asn1.DERSet;
53
import org.bouncycastle.asn1.DERUTF8String;
54
import org.bouncycastle.asn1.cms.AttributeTable;
55
import org.bouncycastle.asn1.cms.ContentInfo;
56
import org.bouncycastle.cert.X509CertificateHolder;
57
import org.bouncycastle.cms.CMSException;
58
import org.bouncycastle.cms.CMSProcessable;
59
import org.bouncycastle.cms.CMSSignedData;
60
import org.bouncycastle.cms.SignerId;
61
import org.bouncycastle.cms.SignerInformation;
62
import org.bouncycastle.cms.SignerInformationStore;
63
import org.bouncycastle.operator.DefaultAlgorithmNameFinder;
64
import org.bouncycastle.util.encoders.Hex;
65

66
import net.jsign.asn1.authenticode.AuthenticodeObjectIdentifiers;
67
import net.jsign.timestamp.Timestamper;
68
import net.jsign.timestamp.TimestampingMode;
69

70
/**
71
 * Helper class to create AuthenticodeSigner instances with untyped parameters.
72
 * This is used internally to share the parameter validation logic
73
 * between the Ant task, the Maven/Gradle plugins and the CLI tool.
74
 *
75
 * @since 2.0
76
 */
77
class SignerHelper {
78
    public static final String PARAM_COMMAND = "command";
79
    public static final String PARAM_KEYSTORE = "keystore";
80
    public static final String PARAM_STOREPASS = "storepass";
81
    public static final String PARAM_STORETYPE = "storetype";
82
    public static final String PARAM_ALIAS = "alias";
83
    public static final String PARAM_KEYPASS = "keypass";
84
    public static final String PARAM_KEYFILE = "keyfile";
85
    public static final String PARAM_CERTFILE = "certfile";
86
    public static final String PARAM_ALG = "alg";
87
    public static final String PARAM_TSAURL = "tsaurl";
88
    public static final String PARAM_TSMODE = "tsmode";
89
    public static final String PARAM_TSRETRIES = "tsretries";
90
    public static final String PARAM_TSRETRY_WAIT = "tsretrywait";
91
    public static final String PARAM_NAME = "name";
92
    public static final String PARAM_URL = "url";
93
    public static final String PARAM_PROXY_URL = "proxyUrl";
94
    public static final String PARAM_PROXY_USER = "proxyUser";
95
    public static final String PARAM_PROXY_PASS = "proxyPass";
96
    public static final String PARAM_REPLACE = "replace";
97
    public static final String PARAM_ENCODING = "encoding";
98
    public static final String PARAM_DETACHED = "detached";
99
    public static final String PARAM_FORMAT = "format";
100
    public static final String PARAM_VALUE = "value";
101

102
    private final Logger log = Logger.getLogger(getClass().getName());
1✔
103

104
    /** The name used to refer to a configuration parameter */
105
    private final String parameterName;
106

107
    /** The command to execute */
108
    private String command = "sign";
1✔
109

110
    private final KeyStoreBuilder ksparams;
111
    private String alias;
112
    private String tsaurl;
113
    private String tsmode;
114
    private int tsretries = -1;
1✔
115
    private int tsretrywait = -1;
1✔
116
    private String alg;
117
    private String name;
118
    private String url;
119
    private String proxyUrl;
120
    private String proxyUser;
121
    private String proxyPass;
122
    private boolean replace;
123
    private Charset encoding;
124
    private boolean detached;
125
    private String format;
126
    private String value;
127

128
    private AuthenticodeSigner signer;
129

130
    public SignerHelper(String parameterName) {
1✔
131
        this.parameterName = parameterName;
1✔
132
        this.ksparams = new KeyStoreBuilder(parameterName);
1✔
133
    }
1✔
134

135
    public SignerHelper command(String command) {
136
        this.command = command;
1✔
137
        return this;
1✔
138
    }
139

140
    public SignerHelper keystore(String keystore) {
141
        ksparams.keystore(keystore);
1✔
142
        signer = null;
1✔
143
        return this;
1✔
144
    }
145

146
    public SignerHelper storepass(String storepass) {
147
        ksparams.storepass(storepass);
1✔
148
        signer = null;
1✔
149
        return this;
1✔
150
    }
151

152
    public SignerHelper storetype(String storetype) {
153
        ksparams.storetype(storetype);
1✔
154
        signer = null;
1✔
155
        return this;
1✔
156
    }
157

158
    public SignerHelper alias(String alias) {
159
        this.alias = alias;
1✔
160
        signer = null;
1✔
161
        return this;
1✔
162
    }
163

164
    public SignerHelper keypass(String keypass) {
165
        ksparams.keypass(keypass);
1✔
166
        signer = null;
1✔
167
        return this;
1✔
168
    }
169

170
    public SignerHelper keyfile(String keyfile) {
171
        ksparams.keyfile(keyfile);
1✔
172
        signer = null;
1✔
173
        return this;
1✔
174
    }
175

176
    public SignerHelper keyfile(File keyfile) {
177
        ksparams.keyfile(keyfile);
1✔
178
        signer = null;
1✔
179
        return this;
1✔
180
    }
181

182
    public SignerHelper certfile(String certfile) {
183
        ksparams.certfile(certfile);
1✔
184
        signer = null;
1✔
185
        return this;
1✔
186
    }
187

188
    public SignerHelper certfile(File certfile) {
189
        ksparams.certfile(certfile);
1✔
190
        signer = null;
1✔
191
        return this;
1✔
192
    }
193

194
    public SignerHelper alg(String alg) {
195
        this.alg = alg;
1✔
196
        signer = null;
1✔
197
        return this;
1✔
198
    }
199

200
    public SignerHelper tsaurl(String tsaurl) {
201
        this.tsaurl = tsaurl;
1✔
202
        signer = null;
1✔
203
        return this;
1✔
204
    }
205

206
    public SignerHelper tsmode(String tsmode) {
207
        this.tsmode = tsmode;
1✔
208
        signer = null;
1✔
209
        return this;
1✔
210
    }
211

212
    public SignerHelper tsretries(int tsretries) {
213
        this.tsretries = tsretries;
1✔
214
        signer = null;
1✔
215
        return this;
1✔
216
    }
217

218
    public SignerHelper tsretrywait(int tsretrywait) {
219
        this.tsretrywait = tsretrywait;
1✔
220
        signer = null;
1✔
221
        return this;
1✔
222
    }
223

224
    public SignerHelper name(String name) {
225
        this.name = name;
1✔
226
        signer = null;
1✔
227
        return this;
1✔
228
    }
229

230
    public SignerHelper url(String url) {
231
        this.url = url;
1✔
232
        signer = null;
1✔
233
        return this;
1✔
234
    }
235

236
    public SignerHelper proxyUrl(String proxyUrl) {
237
        this.proxyUrl = proxyUrl;
1✔
238
        signer = null;
1✔
239
        return this;
1✔
240
    }
241

242
    public SignerHelper proxyUser(String proxyUser) {
243
        this.proxyUser = proxyUser;
1✔
244
        signer = null;
1✔
245
        return this;
1✔
246
    }
247

248
    public SignerHelper proxyPass(String proxyPass) {
249
        this.proxyPass = proxyPass;
1✔
250
        signer = null;
1✔
251
        return this;
1✔
252
    }
253

254
    public SignerHelper replace(boolean replace) {
255
        this.replace = replace;
1✔
256
        signer = null;
1✔
257
        return this;
1✔
258
    }
259

260
    public SignerHelper encoding(String encoding) {
261
        this.encoding = Charset.forName(encoding);
1✔
262
        return this;
1✔
263
    }
264

265
    public SignerHelper detached(boolean detached) {
266
        this.detached = detached;
1✔
267
        return this;
1✔
268
    }
269

270
    public SignerHelper format(String format) {
271
        this.format = format;
1✔
272
        return this;
1✔
273
    }
274

275
    public SignerHelper value(String value) {
276
        this.value = value;
1✔
277
        return this;
1✔
278
    }
279

280
    public SignerHelper param(String key, String value) {
281
        if (value == null) {
1✔
282
            return this;
1✔
283
        }
284
        
285
        switch (key) {
1✔
286
            case PARAM_COMMAND:    return command(value);
×
287
            case PARAM_KEYSTORE:   return keystore(value);
1✔
288
            case PARAM_STOREPASS:  return storepass(value);
1✔
289
            case PARAM_STORETYPE:  return storetype(value);
1✔
290
            case PARAM_ALIAS:      return alias(value);
1✔
291
            case PARAM_KEYPASS:    return keypass(value);
1✔
292
            case PARAM_KEYFILE:    return keyfile(value);
1✔
293
            case PARAM_CERTFILE:   return certfile(value);
1✔
294
            case PARAM_ALG:        return alg(value);
1✔
295
            case PARAM_TSAURL:     return tsaurl(value);
1✔
296
            case PARAM_TSMODE:     return tsmode(value);
1✔
297
            case PARAM_TSRETRIES:  return tsretries(Integer.parseInt(value));
1✔
298
            case PARAM_TSRETRY_WAIT: return tsretrywait(Integer.parseInt(value));
1✔
299
            case PARAM_NAME:       return name(value);
1✔
300
            case PARAM_URL:        return url(value);
1✔
301
            case PARAM_PROXY_URL:  return proxyUrl(value);
1✔
302
            case PARAM_PROXY_USER: return proxyUser(value);
1✔
303
            case PARAM_PROXY_PASS: return proxyPass(value);
1✔
304
            case PARAM_REPLACE:    return replace("true".equalsIgnoreCase(value));
×
305
            case PARAM_ENCODING:   return encoding(value);
1✔
306
            case PARAM_DETACHED:   return detached("true".equalsIgnoreCase(value));
×
307
            case PARAM_FORMAT:     return format(value);
×
308
            case PARAM_VALUE:      return value(value);
1✔
309
            default:
310
                throw new IllegalArgumentException("Unknown " + parameterName + ": " + key);
×
311
        }
312
    }
313

314
    void setBaseDir(File basedir) {
315
        ksparams.setBaseDir(basedir);
1✔
316
    }
1✔
317

318
    public void execute(String file) throws SignerException {
319
        execute(ksparams.createFile(file));
×
320
    }
×
321

322
    public void execute(File file) throws SignerException {
323
        switch (command) {
1✔
324
            case "sign":
325
                sign(file);
1✔
326
                break;
1✔
327
            case "timestamp":
328
                timestamp(file);
1✔
329
                break;
1✔
330
            case "extract":
331
                extract(file);
1✔
332
                break;
1✔
333
            case "remove":
334
                remove(file);
1✔
335
                break;
1✔
336
            case "tag":
337
                tag(file);
1✔
338
                break;
1✔
339
            default:
340
                throw new SignerException("Unknown command '" + command + "'");
1✔
341
        }
342
    }
1✔
343

344
    private AuthenticodeSigner build() throws SignerException {
345
        try {
346
            initializeProxy(proxyUrl, proxyUser, proxyPass);
1✔
347
        } catch (Exception e) {
×
348
            throw new SignerException("Couldn't initialize proxy", e);
×
349
        }
1✔
350

351
        KeyStore ks;
352
        try {
353
            ks = ksparams.build();
1✔
354
        } catch (KeyStoreException e) {
1✔
355
            throw new SignerException("Failed to load the keystore " + (ksparams.keystore() != null ? ksparams.keystore() : ""), e);
1✔
356
        }
1✔
357
        KeyStoreType storetype = ksparams.storetype();
1✔
358
        Provider provider = ksparams.provider();
1✔
359

360
        Set<String> aliases = null;
1✔
361
        if (alias == null) {
1✔
362
            // guess the alias if there is only one in the keystore
363
            try {
364
                aliases = storetype.getAliases(ks);
1✔
365
            } catch (KeyStoreException e) {
×
366
                throw new SignerException(e.getMessage(), e);
×
367
            }
1✔
368

369
            if (aliases.isEmpty()) {
1✔
370
                throw new SignerException("No certificate found in the keystore " + (provider != null ? provider.getName() : ksparams.keystore()));
×
371
            } else if (aliases.size() == 1) {
1✔
372
                alias = aliases.iterator().next();
1✔
373
            } else {
374
                throw new SignerException("alias " + parameterName + " must be set to select a certificate (available aliases: " + String.join(", ", aliases) + ")");
1✔
375
            }
376
        }
377

378
        Certificate[] chain;
379
        if (ksparams.certfile() != null) {
1✔
380
            // replace the certificate chain from the keystore with the complete chain from file
381
            try {
382
                chain = CertificateUtils.loadCertificateChain(ksparams.certfile());
1✔
383
            } catch (Exception e) {
×
384
                throw new SignerException("Failed to load the certificate from " + ksparams.certfile(), e);
×
385
            }
1✔
386
        } else {
387
            try {
388
                chain = ks.getCertificateChain(alias);
1✔
389
            } catch (KeyStoreException e) {
×
390
                throw new SignerException(e.getMessage(), e);
×
391
            }
1✔
392
            if (chain == null) {
1✔
393
                String message = "No certificate found under the alias '" + alias + "' in the keystore " + (provider != null ? provider.getName() : ksparams.keystore());
1✔
394
                if (aliases == null) {
1✔
395
                    try {
396
                        aliases = new LinkedHashSet<>(Collections.list(ks.aliases()));
1✔
397
                        if (aliases.isEmpty()) {
1✔
398
                            message = "No certificate found in the keystore " + (provider != null ? provider.getName() : ksparams.keystore());
1✔
399
                        } else if (aliases.contains(alias)) {
1✔
400
                            message = "The keystore password must be specified";
1✔
401
                        } else {
402
                            message += " (available aliases: " + String.join(", ", aliases) + ")";
1✔
403
                        }
404
                    } catch (KeyStoreException e) {
×
405
                        message += " (couldn't load the list of available aliases: " + e.getMessage() + ")";
×
406
                    }
1✔
407
                }
408
                throw new SignerException(message);
1✔
409
            }
410
        }
411

412
        String keypass = ksparams.keypass();
1✔
413
        char[] password = keypass != null ? keypass.toCharArray() : new char[0];
1✔
414

415
        PrivateKey privateKey;
416
        try {
417
            privateKey = (PrivateKey) ks.getKey(alias, password);
1✔
418
        } catch (Exception e) {
1✔
419
            throw new SignerException("Failed to retrieve the private key from the keystore", e);
1✔
420
        }
1✔
421

422
        if (alg != null && DigestAlgorithm.of(alg) == null) {
1✔
423
            throw new SignerException("The digest algorithm " + alg + " is not supported");
1✔
424
        }
425

426
        // enable timestamping with Azure Trusted Signing
427
        if (tsaurl == null && storetype == KeyStoreType.TRUSTEDSIGNING) {
1✔
428
            tsaurl = "http://timestamp.acs.microsoft.com/";
×
429
            tsmode = TimestampingMode.RFC3161.name();
×
430
            tsretries = 3;
×
431
        }
432
        
433
        // configure the signer
434
        return new AuthenticodeSigner(chain, privateKey)
1✔
435
                .withProgramName(name)
1✔
436
                .withProgramURL(url)
1✔
437
                .withDigestAlgorithm(DigestAlgorithm.of(alg))
1✔
438
                .withSignatureProvider(provider)
1✔
439
                .withSignaturesReplaced(replace)
1✔
440
                .withTimestamping(tsaurl != null || tsmode != null)
1✔
441
                .withTimestampingMode(tsmode != null ? TimestampingMode.of(tsmode) : TimestampingMode.AUTHENTICODE)
1✔
442
                .withTimestampingRetries(tsretries)
1✔
443
                .withTimestampingRetryWait(tsretrywait)
1✔
444
                .withTimestampingAuthority(tsaurl != null ? tsaurl.split(",") : null);
1✔
445
    }
446

447
    public void sign(String file) throws SignerException {
448
        sign(ksparams.createFile(file));
×
449
    }
×
450

451
    public void sign(File file) throws SignerException {
452
        if (file == null) {
1✔
453
            throw new SignerException("No file specified");
1✔
454
        }
455
        if (!file.exists()) {
1✔
456
            throw new SignerException("The file " + file + " couldn't be found");
1✔
457
        }
458
        
459
        try (Signable signable = Signable.of(file, encoding)) {
1✔
460
            File detachedSignature = getDetachedSignature(file);
1✔
461
            if (detached && detachedSignature.exists()) {
1✔
462
                try {
463
                    log.info("Attaching Authenticode signature to " + file);
1✔
464
                    attach(signable, detachedSignature);
1✔
465
                } catch (Exception e) {
×
466
                    throw new SignerException("Couldn't attach the signature to " + file, e);
×
467
                }
1✔
468

469
            } else {
470
                if (signer == null) {
1✔
471
                    signer = build();
1✔
472
                }
473

474
                log.info("Adding Authenticode signature to " + file);
1✔
475
                signer.sign(signable);
1✔
476

477
                if (detached) {
1✔
478
                    detach(signable, detachedSignature);
1✔
479
                }
480
            }
481

482
        } catch (UnsupportedOperationException | IllegalArgumentException e) {
1✔
483
            throw new SignerException(e.getMessage(), e);
1✔
484
        } catch (SignerException e) {
1✔
485
            throw e;
1✔
486
        } catch (Exception e) {
1✔
487
            throw new SignerException("Couldn't sign " + file, e);
1✔
488
        }
1✔
489
    }
1✔
490

491
    private void attach(Signable signable, File detachedSignature) throws IOException, CMSException {
492
        byte[] signatureBytes = Files.readAllBytes(detachedSignature.toPath());
1✔
493
        CMSSignedData signedData = new CMSSignedData((CMSProcessable) null, ContentInfo.getInstance(new ASN1InputStream(signatureBytes).readObject()));
1✔
494

495
        signable.setSignatures(SignatureUtils.getSignatures(signedData));
1✔
496
        signable.save();
1✔
497
        // todo warn if the hashes don't match
498
    }
1✔
499

500
    private void detach(Signable signable, File detachedSignature) throws IOException {
501
        List<CMSSignedData> signatures = signable.getSignatures();
1✔
502

503
        // ensure the secondary signatures are nested in the first one (for EFI files)
504
        CMSSignedData signedData = signatures.get(0);
1✔
505
        if (signatures.size() > 1) {
1✔
506
            List<CMSSignedData> nestedSignatures = signatures.subList(1, signatures.size());
1✔
507
            signedData = SignatureUtils.addNestedSignature(signedData, true, nestedSignatures.toArray(new CMSSignedData[0]));
1✔
508
        }
509

510
        byte[] content = signedData.toASN1Structure().getEncoded("DER");
1✔
511
        if (format == null || "DER".equalsIgnoreCase(format)) {
1✔
512
            Files.write(detachedSignature.toPath(), content);
1✔
513
        } else if ("PEM".equalsIgnoreCase(format)) {
1✔
514
            try (FileWriter out = new FileWriter(detachedSignature)) {
1✔
515
                String encoded = Base64.getEncoder().encodeToString(content);
1✔
516
                out.write("-----BEGIN PKCS7-----\n");
1✔
517
                for (int i = 0; i < encoded.length(); i += 64) {
1✔
518
                    out.write(encoded.substring(i, Math.min(i + 64, encoded.length())));
1✔
519
                    out.write('\n');
1✔
520
                }
521
                out.write("-----END PKCS7-----\n");
1✔
522
            }
523
        } else {
524
            throw new IllegalArgumentException("Unknown output format '" + format + "'");
1✔
525
        }
526
    }
1✔
527

528
    private File getDetachedSignature(File file) {
529
        return new File(file.getParentFile(), file.getName() + ".sig");
1✔
530
    }
531

532
    private void extract(File file) throws SignerException {
533
        if (!file.exists()) {
1✔
534
            throw new SignerException("Couldn't find " + file);
1✔
535
        }
536

537
        try (Signable signable = Signable.of(file)) {
1✔
538
            List<CMSSignedData> signatures = signable.getSignatures();
1✔
539
            if (signatures.isEmpty()) {
1✔
540
                throw new SignerException("No signature found in " + file);
1✔
541
            }
542

543
            File detachedSignature = getDetachedSignature(file);
1✔
544
            if ("PEM".equalsIgnoreCase(format)) {
1✔
545
                detachedSignature = new File(detachedSignature.getParentFile(), detachedSignature.getName() + ".pem");
1✔
546
            }
547
            log.info("Extracting signature to " + detachedSignature);
1✔
548
            detach(signable, detachedSignature);
1✔
549
        } catch (UnsupportedOperationException | IllegalArgumentException e) {
1✔
550
            throw new SignerException(e.getMessage(), e);
1✔
551
        } catch (SignerException e) {
1✔
552
            throw e;
1✔
553
        } catch (Exception e) {
×
554
            throw new SignerException("Couldn't extract the signature from " + file, e);
×
555
        }
1✔
556
    }
1✔
557

558
    private void remove(File file) throws SignerException {
559
        if (!file.exists()) {
1✔
560
            throw new SignerException("Couldn't find " + file);
1✔
561
        }
562

563
        try (Signable signable = Signable.of(file)) {
1✔
564
            List<CMSSignedData> signatures = signable.getSignatures();
1✔
565
            if (signatures.isEmpty()) {
1✔
566
                log.severe("No signature found in " + file);
1✔
567
                return;
1✔
568
            }
569

570
            log.info("Removing " + signatures.size() + " signature" + (signatures.size() > 1 ? "s" : "") + " from " + file);
1✔
571
            signable.setSignatures(null);
1✔
572
            signable.save();
1✔
573
        } catch (UnsupportedOperationException | IllegalArgumentException e) {
1✔
574
            throw new SignerException(e.getMessage(), e);
×
575
        } catch (Exception e) {
×
576
            throw new SignerException("Couldn't remove the signature from " + file, e);
×
577
        }
1✔
578
    }
1✔
579

580
    private void tag(File file) throws SignerException {
581
        if (!file.exists()) {
1✔
582
            throw new SignerException("Couldn't find " + file);
1✔
583
        }
584

585
        try (Signable signable = Signable.of(file)) {
1✔
586
            List<CMSSignedData> signatures = signable.getSignatures();
1✔
587
            if (signatures.isEmpty()) {
1✔
588
                throw new SignerException("No signature found in " + file);
1✔
589
            }
590

591
            log.info("Adding tag to " + file);
1✔
592
            signatures.set(0, addUnsignedAttribute(signatures.get(0), AuthenticodeObjectIdentifiers.JSIGN_UNSIGNED_DATA_OBJID, getTagValue()));
1✔
593
            signable.setSignatures(signatures);
1✔
594
            signable.save();
1✔
595
        } catch (SignerException e) {
1✔
596
            throw e;
1✔
597
        } catch (Exception e) {
1✔
598
            throw new SignerException("Couldn't modify the signature of " + file, e);
1✔
599
        }
1✔
600
    }
1✔
601

602
    private CMSSignedData addUnsignedAttribute(CMSSignedData signature, ASN1ObjectIdentifier oid, ASN1Encodable value) {
603
        SignerInformationStore store = signature.getSignerInfos();
1✔
604
        Collection<SignerInformation> signers = store.getSigners();
1✔
605
        SignerInformation signer = signers.iterator().next();
1✔
606

607
        AttributeTable attributes = signer.getUnsignedAttributes();
1✔
608
        if (attributes == null) {
1✔
609
            attributes = new AttributeTable(new DERSet());
1✔
610
        }
611
        attributes = attributes.add(oid, value);
1✔
612

613
        signers.remove(signer);
1✔
614
        signers.add(SignerInformation.replaceUnsignedAttributes(signer, attributes));
1✔
615
        return CMSSignedData.replaceSigners(signature, new SignerInformationStore(signers));
1✔
616
    }
617

618
    private ASN1Encodable getTagValue() throws IOException {
619
        if (value == null) {
1✔
620
            byte[] array = new byte[1024];
1✔
621
            String begin = "-----BEGIN TAG-----";
1✔
622
            System.arraycopy(begin.getBytes(), 0, array, 0, begin.length());
1✔
623
            String end = "-----END TAG-----";
1✔
624
            System.arraycopy(end.getBytes(), 0, array, array.length - end.length(), end.length());
1✔
625
            return new DEROctetString(array);
1✔
626

627
        } else if (value.startsWith("0x")) {
1✔
628
            byte[] array = Hex.decode(value.substring(2));
1✔
629
            return new DEROctetString(array);
1✔
630

631
        } else if (value.startsWith("file:")) {
1✔
632
            byte[] array = Files.readAllBytes(new File(value.substring("file:".length())).toPath());
1✔
633
            return new DEROctetString(array);
1✔
634

635
        } else {
636
            return new DERUTF8String(value);
1✔
637
        }
638
    }
639

640
    private void timestamp(File file) throws SignerException {
641
        if (!file.exists()) {
1✔
642
            throw new SignerException("Couldn't find " + file);
1✔
643
        }
644

645
        try {
646
            initializeProxy(proxyUrl, proxyUser, proxyPass);
1✔
647
        } catch (Exception e) {
×
648
            throw new SignerException("Couldn't initialize proxy", e);
×
649
        }
1✔
650

651
        try (Signable signable = Signable.of(file)) {
1✔
652
            if (signable.getSignatures().isEmpty()) {
1✔
653
                throw new SignerException("No signature found in " + file);
1✔
654
            }
655

656
            Timestamper timestamper = Timestamper.create(tsmode != null ? TimestampingMode.of(tsmode) : TimestampingMode.AUTHENTICODE);
1✔
657
            timestamper.setRetries(tsretries);
1✔
658
            timestamper.setRetryWait(tsretrywait);
1✔
659
            if (tsaurl != null) {
1✔
660
                timestamper.setURLs(tsaurl.split(","));
1✔
661
            }
662
            DigestAlgorithm digestAlgorithm = alg != null ? DigestAlgorithm.of(alg) : DigestAlgorithm.getDefault();
1✔
663

664
            List<CMSSignedData> signatures = new ArrayList<>();
1✔
665
            for (CMSSignedData signature : signable.getSignatures()) {
1✔
666
                SignerInformation signerInformation = signature.getSignerInfos().iterator().next();
1✔
667
                SignerId signerId = signerInformation.getSID();
1✔
668
                X509CertificateHolder certificate = (X509CertificateHolder) signature.getCertificates().getMatches(signerId).iterator().next();
1✔
669

670
                String digestAlgorithmName = new DefaultAlgorithmNameFinder().getAlgorithmName(signerInformation.getDigestAlgorithmID()); 
1✔
671
                String keyAlgorithmName = new DefaultAlgorithmNameFinder().getAlgorithmName(new ASN1ObjectIdentifier(signerInformation.getEncryptionAlgOID()));
1✔
672
                String name = digestAlgorithmName + "/" + keyAlgorithmName + " signature from '" + certificate.getSubject() + "'";
1✔
673

674
                if (SignatureUtils.isTimestamped(signature) && !replace) {
1✔
675
                    log.fine(name + " already timestamped");
1✔
676
                    signatures.add(signature);
1✔
677
                    continue;
1✔
678
                }
679

680
                boolean expired = certificate.getNotAfter().before(new Date());
1✔
681
                if (expired) {
1✔
682
                    log.fine(name + " is expired, skipping");
×
683
                    signatures.add(signature);
×
684
                    continue;
×
685
                }
686

687
                log.info("Adding timestamp to " + name);
1✔
688
                signature = SignatureUtils.removeTimestamp(signature);
1✔
689
                signature = timestamper.timestamp(digestAlgorithm, signature);
1✔
690

691
                signatures.add(signature);
1✔
692
            }
1✔
693

694
            signable.setSignatures(signatures);
1✔
695
            signable.save();
1✔
696
        } catch (IOException | CMSException e) {
×
697
            throw new SignerException("Couldn't timestamp " + file, e);
×
698
        }
1✔
699
    }
1✔
700

701
    /**
702
     * Initializes the proxy.
703
     *
704
     * @param proxyUrl       the url of the proxy (either as hostname:port or http[s]://hostname:port)
705
     * @param proxyUser      the username for the proxy authentication
706
     * @param proxyPassword  the password for the proxy authentication
707
     */
708
    private void initializeProxy(String proxyUrl, final String proxyUser, final String proxyPassword) throws MalformedURLException {
709
        // Do nothing if there is no proxy url.
710
        if (proxyUrl != null && !proxyUrl.trim().isEmpty()) {
1✔
711
            if (!proxyUrl.trim().startsWith("http")) {
1✔
712
                proxyUrl = "http://" + proxyUrl.trim();
1✔
713
            }
714
            final URL url = new URL(proxyUrl);
1✔
715
            final int port = url.getPort() < 0 ? 80 : url.getPort();
1✔
716

717
            ProxySelector.setDefault(new ProxySelector() {
1✔
718
                public List<Proxy> select(URI uri) {
719
                    Proxy proxy;
720
                    if (uri.getScheme().equals("socket")) {
1✔
721
                        proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(url.getHost(), port));
×
722
                    } else {
723
                        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), port));
1✔
724
                    }
725
                    log.fine("Proxy selected for " + uri + " : " + proxy);
1✔
726
                    return Collections.singletonList(proxy);
1✔
727
                }
728

729
                public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
730
                }
×
731
            });
732

733
            if (proxyUser != null && !proxyUser.isEmpty() && proxyPassword != null) {
1✔
734
                Authenticator.setDefault(new Authenticator() {
1✔
735
                    protected PasswordAuthentication getPasswordAuthentication() {
736
                        return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
1✔
737
                    }
738
                });
739
            }
740
        }
741
    }
1✔
742
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc