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

ebourg / jsign / #409

08 Jul 2026 03:29PM UTC coverage: 80.912% (+0.1%) from 80.783%
#409

push

ebourg
Improved the test coverage of NAVX file parsing

1 of 1 new or added line in 1 file covered. (100.0%)

49 existing lines in 3 files now uncovered.

5129 of 6339 relevant lines covered (80.91%)

0.81 hits per line

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

89.67
/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.nio.charset.Charset;
23
import java.nio.file.Files;
24
import java.security.KeyStore;
25
import java.security.KeyStoreException;
26
import java.security.PrivateKey;
27
import java.security.Provider;
28
import java.security.cert.Certificate;
29
import java.util.ArrayList;
30
import java.util.Base64;
31
import java.util.Collection;
32
import java.util.Collections;
33
import java.util.Date;
34
import java.util.LinkedHashSet;
35
import java.util.List;
36
import java.util.Set;
37
import java.util.logging.Logger;
38

39
import org.bouncycastle.asn1.ASN1Encodable;
40
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
41
import org.bouncycastle.asn1.DEROctetString;
42
import org.bouncycastle.asn1.DERSet;
43
import org.bouncycastle.asn1.DERUTF8String;
44
import org.bouncycastle.asn1.cms.AttributeTable;
45
import org.bouncycastle.cert.X509CertificateHolder;
46
import org.bouncycastle.cms.CMSException;
47
import org.bouncycastle.cms.CMSSignedData;
48
import org.bouncycastle.cms.SignerId;
49
import org.bouncycastle.cms.SignerInformation;
50
import org.bouncycastle.cms.SignerInformationStore;
51
import org.bouncycastle.operator.DefaultAlgorithmNameFinder;
52
import org.bouncycastle.util.encoders.Hex;
53

54
import net.jsign.asn1.authenticode.AuthenticodeObjectIdentifiers;
55
import net.jsign.timestamp.Timestamper;
56
import net.jsign.timestamp.TimestampingMode;
57

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

92
    private final Logger log = Logger.getLogger(getClass().getName());
1✔
93

94
    /** The name used to refer to a configuration parameter */
95
    private final String parameterName;
96

97
    /** The command to execute */
98
    private String command = "sign";
1✔
99

100
    private final KeyStoreBuilder ksparams;
101
    private String alias;
102
    private String tsaurl;
103
    private String tsmode;
104
    private int tsretries = -1;
1✔
105
    private int tsretrywait = -1;
1✔
106
    private String alg;
107
    private String name;
108
    private String url;
109
    private final ProxySettings proxySettings = new ProxySettings();
1✔
110
    private boolean replace;
111
    private boolean lazy;
112
    private Charset encoding;
113
    private boolean detached;
114
    private String format;
115
    private String value;
116

117
    private AuthenticodeSigner signer;
118

119
    public SignerHelper(String parameterName) {
1✔
120
        this.parameterName = parameterName;
1✔
121
        this.ksparams = new KeyStoreBuilder(parameterName);
1✔
122
    }
1✔
123

124
    public SignerHelper command(String command) {
125
        this.command = command;
1✔
126
        return this;
1✔
127
    }
128

129
    public SignerHelper keystore(String keystore) {
130
        ksparams.keystore(keystore);
1✔
131
        signer = null;
1✔
132
        return this;
1✔
133
    }
134

135
    public SignerHelper storepass(String storepass) {
136
        ksparams.storepass(storepass);
1✔
137
        signer = null;
1✔
138
        return this;
1✔
139
    }
140

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

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

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

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

165
    public SignerHelper keyfile(File keyfile) {
166
        ksparams.keyfile(keyfile);
1✔
167
        signer = null;
1✔
168
        return this;
1✔
169
    }
170

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

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

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

189
    public SignerHelper tsaurl(String tsaurl) {
190
        this.tsaurl = tsaurl;
1✔
191
        signer = null;
1✔
192
        return this;
1✔
193
    }
194

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

201
    public SignerHelper tsretries(int tsretries) {
202
        this.tsretries = tsretries;
1✔
203
        signer = null;
1✔
204
        return this;
1✔
205
    }
206

207
    public SignerHelper tsretrywait(int tsretrywait) {
208
        this.tsretrywait = tsretrywait;
1✔
209
        signer = null;
1✔
210
        return this;
1✔
211
    }
212

213
    public SignerHelper name(String name) {
214
        this.name = name;
1✔
215
        signer = null;
1✔
216
        return this;
1✔
217
    }
218

219
    public SignerHelper url(String url) {
220
        this.url = url;
1✔
221
        signer = null;
1✔
222
        return this;
1✔
223
    }
224

225
    public SignerHelper proxyUrl(String proxyUrl) {
226
        this.proxySettings.url = proxyUrl;
1✔
227
        signer = null;
1✔
228
        return this;
1✔
229
    }
230

231
    public SignerHelper proxyUser(String proxyUser) {
232
        this.proxySettings.username = proxyUser;
1✔
233
        signer = null;
1✔
234
        return this;
1✔
235
    }
236

237
    public SignerHelper proxyPass(String proxyPass) {
238
        this.proxySettings.password = proxyPass;
1✔
239
        signer = null;
1✔
240
        return this;
1✔
241
    }
242

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

249
    public SignerHelper replace(boolean replace) {
250
        this.replace = replace;
1✔
251
        signer = null;
1✔
252
        return this;
1✔
253
    }
254

255
    public SignerHelper lazy(boolean lazy) {
256
        this.lazy = lazy;
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✔
UNCOV
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_NON_PROXY_HOSTS: return nonProxyHosts(value);
1✔
UNCOV
305
            case PARAM_REPLACE:    return replace("true".equalsIgnoreCase(value));
×
UNCOV
306
            case PARAM_LAZY:       return lazy("true".equalsIgnoreCase(value));
×
307
            case PARAM_ENCODING:   return encoding(value);
1✔
308
            case PARAM_DETACHED:   return detached("true".equalsIgnoreCase(value));
×
309
            case PARAM_FORMAT:     return format(value);
×
310
            case PARAM_VALUE:      return value(value);
1✔
311
            default:
312
                throw new IllegalArgumentException("Unknown " + parameterName + ": " + key);
×
313
        }
314
    }
315

316
    void setBaseDir(File basedir) {
317
        ksparams.setBaseDir(basedir);
1✔
318
    }
1✔
319

320
    public void execute(String file) throws SignerException {
UNCOV
321
        execute(ksparams.createFile(file));
×
UNCOV
322
    }
×
323

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

346
    private AuthenticodeSigner build() throws SignerException {
347
        try {
348
            proxySettings.initializeProxy();
1✔
UNCOV
349
        } catch (Exception e) {
×
UNCOV
350
            throw new SignerException("Couldn't initialize proxy", e);
×
351
        }
1✔
352

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

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

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

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

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

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

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

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

449
    public void sign(String file) throws SignerException {
UNCOV
450
        sign(ksparams.createFile(file));
×
UNCOV
451
    }
×
452

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

471
            } else {
472
                if (lazy && !signable.getSignatures().isEmpty()) {
1✔
473
                    log.info("Skipping already signed file " + file);
1✔
474
                    return;
1✔
475
                }
476

477
                if (signer == null) {
1✔
478
                    signer = build();
1✔
479
                }
480

481
                log.info("Adding Authenticode signature to " + file);
1✔
482
                signer.sign(signable);
1✔
483

484
                if (detached) {
1✔
485
                    detach(signable, detachedSignature);
1✔
486
                }
487
            }
488

489
        } catch (UnsupportedOperationException | IllegalArgumentException e) {
1✔
490
            throw new SignerException(e.getMessage(), e);
1✔
491
        } catch (SignerException e) {
1✔
492
            throw e;
1✔
493
        } catch (Exception e) {
1✔
494
            throw new SignerException("Couldn't sign " + file, e);
1✔
495
        }
1✔
496
    }
1✔
497

498
    private void attach(Signable signable, File detachedSignature) throws IOException {
499
        byte[] signatureBytes = Files.readAllBytes(detachedSignature.toPath());
1✔
500
        signable.setSignatures(SignatureUtils.getSignatures(signatureBytes));
1✔
501
        signable.save();
1✔
502
        // todo warn if the hashes don't match
503
    }
1✔
504

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

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

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

533
    private File getDetachedSignature(File file) {
534
        return new File(file.getParentFile(), file.getName() + ".sig");
1✔
535
    }
536

537
    private void extract(File file) throws SignerException {
538
        if (!file.exists()) {
1✔
539
            throw new SignerException("Couldn't find " + file);
1✔
540
        }
541

542
        try (Signable signable = Signable.of(file)) {
1✔
543
            List<CMSSignedData> signatures = signable.getSignatures();
1✔
544
            if (signatures.isEmpty()) {
1✔
545
                throw new SignerException("No signature found in " + file);
1✔
546
            }
547

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

563
    private void remove(File file) throws SignerException {
564
        if (!file.exists()) {
1✔
565
            throw new SignerException("Couldn't find " + file);
1✔
566
        }
567

568
        try (Signable signable = Signable.of(file)) {
1✔
569
            List<CMSSignedData> signatures = signable.getSignatures();
1✔
570
            if (signatures.isEmpty()) {
1✔
571
                log.severe("No signature found in " + file);
1✔
572
                return;
1✔
573
            }
574

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

585
    private void tag(File file) throws SignerException {
586
        if (!file.exists()) {
1✔
587
            throw new SignerException("Couldn't find " + file);
1✔
588
        }
589

590
        try (Signable signable = Signable.of(file)) {
1✔
591
            List<CMSSignedData> signatures = signable.getSignatures();
1✔
592
            if (signatures.isEmpty()) {
1✔
593
                throw new SignerException("No signature found in " + file);
1✔
594
            }
595

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

607
    private CMSSignedData addUnsignedAttribute(CMSSignedData signature, ASN1ObjectIdentifier oid, ASN1Encodable value) {
608
        SignerInformationStore store = signature.getSignerInfos();
1✔
609
        Collection<SignerInformation> signers = store.getSigners();
1✔
610
        SignerInformation signer = signers.iterator().next();
1✔
611

612
        AttributeTable attributes = signer.getUnsignedAttributes();
1✔
613
        if (attributes == null) {
1✔
614
            attributes = new AttributeTable(new DERSet());
1✔
615
        }
616
        attributes = attributes.add(oid, value);
1✔
617

618
        signers.remove(signer);
1✔
619
        signers.add(SignerInformation.replaceUnsignedAttributes(signer, attributes));
1✔
620
        return CMSSignedData.replaceSigners(signature, new SignerInformationStore(signers));
1✔
621
    }
622

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

632
        } else if (value.startsWith("0x")) {
1✔
633
            byte[] array = Hex.decode(value.substring(2));
1✔
634
            return new DEROctetString(array);
1✔
635

636
        } else if (value.startsWith("file:")) {
1✔
637
            byte[] array = Files.readAllBytes(new File(value.substring("file:".length())).toPath());
1✔
638
            return new DEROctetString(array);
1✔
639

640
        } else {
641
            return new DERUTF8String(value);
1✔
642
        }
643
    }
644

645
    private void timestamp(File file) throws SignerException {
646
        if (!file.exists()) {
1✔
647
            throw new SignerException("Couldn't find " + file);
1✔
648
        }
649

650
        try {
651
            proxySettings.initializeProxy();
1✔
UNCOV
652
        } catch (Exception e) {
×
UNCOV
653
            throw new SignerException("Couldn't initialize proxy", e);
×
654
        }
1✔
655

656
        try (Signable signable = Signable.of(file)) {
1✔
657
            if (signable.getSignatures().isEmpty()) {
1✔
658
                throw new SignerException("No signature found in " + file);
1✔
659
            }
660

661
            Timestamper timestamper = Timestamper.create(tsmode != null ? TimestampingMode.of(tsmode) : TimestampingMode.AUTHENTICODE);
1✔
662
            timestamper.setRetries(tsretries);
1✔
663
            timestamper.setRetryWait(tsretrywait);
1✔
664
            if (tsaurl != null) {
1✔
665
                timestamper.setURLs(tsaurl.split(","));
1✔
666
            }
667
            DigestAlgorithm digestAlgorithm = alg != null ? DigestAlgorithm.of(alg) : DigestAlgorithm.getDefault();
1✔
668

669
            List<CMSSignedData> signatures = new ArrayList<>();
1✔
670
            for (CMSSignedData signature : signable.getSignatures()) {
1✔
671
                SignerInformation signerInformation = signature.getSignerInfos().iterator().next();
1✔
672
                SignerId signerId = signerInformation.getSID();
1✔
673
                X509CertificateHolder certificate = (X509CertificateHolder) signature.getCertificates().getMatches(signerId).iterator().next();
1✔
674

675
                String digestAlgorithmName = new DefaultAlgorithmNameFinder().getAlgorithmName(signerInformation.getDigestAlgorithmID()); 
1✔
676
                String keyAlgorithmName = new DefaultAlgorithmNameFinder().getAlgorithmName(new ASN1ObjectIdentifier(signerInformation.getEncryptionAlgOID()));
1✔
677
                String name = digestAlgorithmName + "/" + keyAlgorithmName + " signature from '" + certificate.getSubject() + "'";
1✔
678

679
                if (SignatureUtils.isTimestamped(signature) && !replace) {
1✔
680
                    log.fine(name + " already timestamped");
1✔
681
                    signatures.add(signature);
1✔
682
                    continue;
1✔
683
                }
684

685
                boolean expired = certificate.getNotAfter().before(new Date());
1✔
686
                if (expired) {
1✔
UNCOV
687
                    log.fine(name + " is expired, skipping");
×
UNCOV
688
                    signatures.add(signature);
×
UNCOV
689
                    continue;
×
690
                }
691

692
                log.info("Adding timestamp to " + name);
1✔
693
                signature = SignatureUtils.removeTimestamp(signature);
1✔
694
                signature = timestamper.timestamp(digestAlgorithm, signature);
1✔
695

696
                signatures.add(signature);
1✔
697
            }
1✔
698

699
            signable.setSignatures(signatures);
1✔
700
            signable.save();
1✔
UNCOV
701
        } catch (IOException | CMSException e) {
×
UNCOV
702
            throw new SignerException("Couldn't timestamp " + file, e);
×
703
        }
1✔
704
    }
1✔
705
}
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