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

ebourg / jsign / #429

12 Oct 2026 08:24AM UTC coverage: 80.879% (+0.3%) from 80.604%
#429

push

ebourg
Release version 7.6

5080 of 6281 relevant lines covered (80.88%)

0.81 hits per line

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

89.54
/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.ASN1ObjectIdentifier;
50
import org.bouncycastle.asn1.DEROctetString;
51
import org.bouncycastle.asn1.DERSet;
52
import org.bouncycastle.asn1.DERUTF8String;
53
import org.bouncycastle.asn1.cms.AttributeTable;
54
import org.bouncycastle.cert.X509CertificateHolder;
55
import org.bouncycastle.cms.CMSException;
56
import org.bouncycastle.cms.CMSSignedData;
57
import org.bouncycastle.cms.SignerId;
58
import org.bouncycastle.cms.SignerInformation;
59
import org.bouncycastle.cms.SignerInformationStore;
60
import org.bouncycastle.operator.DefaultAlgorithmNameFinder;
61
import org.bouncycastle.util.encoders.Hex;
62

63
import net.jsign.asn1.authenticode.AuthenticodeObjectIdentifiers;
64
import net.jsign.timestamp.Timestamper;
65
import net.jsign.timestamp.TimestampingMode;
66

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

99
    private final Logger log = Logger.getLogger(getClass().getName());
1 ✔
100

101
    /** The name used to refer to a configuration parameter */
102
    private final String parameterName;
103

104
    /** The command to execute */
105
    private String command = "sign";
1 ✔
106

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

125
    private AuthenticodeSigner signer;
126

127
    public SignerHelper(String parameterName) {
1 ✔
128
        this.parameterName = parameterName;
1 ✔
129
        this.ksparams = new KeyStoreBuilder(parameterName);
1 ✔
130
    }
1 ✔
131

132
    public SignerHelper command(String command) {
133
        this.command = command;
1 ✔
134
        return this;
1 ✔
135
    }
136

137
    public SignerHelper keystore(String keystore) {
138
        ksparams.keystore(keystore);
1 ✔
139
        signer = null;
1 ✔
140
        return this;
1 ✔
141
    }
142

143
    public SignerHelper storepass(String storepass) {
144
        ksparams.storepass(storepass);
1 ✔
145
        signer = null;
1 ✔
146
        return this;
1 ✔
147
    }
148

149
    public SignerHelper storetype(String storetype) {
150
        ksparams.storetype(storetype);
1 ✔
151
        signer = null;
1 ✔
152
        return this;
1 ✔
153
    }
154

155
    public SignerHelper alias(String alias) {
156
        this.alias = alias;
1 ✔
157
        signer = null;
1 ✔
158
        return this;
1 ✔
159
    }
160

161
    public SignerHelper keypass(String keypass) {
162
        ksparams.keypass(keypass);
1 ✔
163
        signer = null;
1 ✔
164
        return this;
1 ✔
165
    }
166

167
    public SignerHelper keyfile(String keyfile) {
168
        ksparams.keyfile(keyfile);
1 ✔
169
        signer = null;
1 ✔
170
        return this;
1 ✔
171
    }
172

173
    public SignerHelper keyfile(File keyfile) {
174
        ksparams.keyfile(keyfile);
1 ✔
175
        signer = null;
1 ✔
176
        return this;
1 ✔
177
    }
178

179
    public SignerHelper certfile(String certfile) {
180
        ksparams.certfile(certfile);
1 ✔
181
        signer = null;
1 ✔
182
        return this;
1 ✔
183
    }
184

185
    public SignerHelper certfile(File certfile) {
186
        ksparams.certfile(certfile);
1 ✔
187
        signer = null;
1 ✔
188
        return this;
1 ✔
189
    }
190

191
    public SignerHelper alg(String alg) {
192
        this.alg = alg;
1 ✔
193
        signer = null;
1 ✔
194
        return this;
1 ✔
195
    }
196

197
    public SignerHelper tsaurl(String tsaurl) {
198
        this.tsaurl = tsaurl;
1 ✔
199
        signer = null;
1 ✔
200
        return this;
1 ✔
201
    }
202

203
    public SignerHelper tsmode(String tsmode) {
204
        this.tsmode = tsmode;
1 ✔
205
        signer = null;
1 ✔
206
        return this;
1 ✔
207
    }
208

209
    public SignerHelper tsretries(int tsretries) {
210
        this.tsretries = tsretries;
1 ✔
211
        signer = null;
1 ✔
212
        return this;
1 ✔
213
    }
214

215
    public SignerHelper tsretrywait(int tsretrywait) {
216
        this.tsretrywait = tsretrywait;
1 ✔
217
        signer = null;
1 ✔
218
        return this;
1 ✔
219
    }
220

221
    public SignerHelper name(String name) {
222
        this.name = name;
1 ✔
223
        signer = null;
1 ✔
224
        return this;
1 ✔
225
    }
226

227
    public SignerHelper url(String url) {
228
        this.url = url;
1 ✔
229
        signer = null;
1 ✔
230
        return this;
1 ✔
231
    }
232

233
    public SignerHelper proxyUrl(String proxyUrl) {
234
        this.proxyUrl = proxyUrl;
1 ✔
235
        signer = null;
1 ✔
236
        return this;
1 ✔
237
    }
238

239
    public SignerHelper proxyUser(String proxyUser) {
240
        this.proxyUser = proxyUser;
1 ✔
241
        signer = null;
1 ✔
242
        return this;
1 ✔
243
    }
244

245
    public SignerHelper proxyPass(String proxyPass) {
246
        this.proxyPass = proxyPass;
1 ✔
247
        signer = null;
1 ✔
248
        return this;
1 ✔
249
    }
250

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

257
    public SignerHelper encoding(String encoding) {
258
        this.encoding = Charset.forName(encoding);
1 ✔
259
        return this;
1 ✔
260
    }
261

262
    public SignerHelper detached(boolean detached) {
263
        this.detached = detached;
1 ✔
264
        return this;
1 ✔
265
    }
266

267
    public SignerHelper format(String format) {
268
        this.format = format;
1 ✔
269
        return this;
1 ✔
270
    }
271

272
    public SignerHelper value(String value) {
273
        this.value = value;
1 ✔
274
        return this;
1 ✔
275
    }
276

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

311
    void setBaseDir(File basedir) {
312
        ksparams.setBaseDir(basedir);
1 ✔
313
    }
1 ✔
314

315
    public void execute(String file) throws SignerException {
316
        execute(ksparams.createFile(file));
×
317
    }
×
318

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

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

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

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

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

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

409
        String keypass = ksparams.keypass();
1 ✔
410
        char[] password = keypass != null ? keypass.toCharArray() : new char[0];
1 ✔
411

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

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

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

444
    public void sign(String file) throws SignerException {
445
        sign(ksparams.createFile(file));
×
446
    }
×
447

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

466
            } else {
467
                if (signer == null) {
1 ✔
468
                    signer = build();
1 ✔
469
                }
470

471
                log.info("Adding Authenticode signature to " + file);
1 ✔
472
                signer.sign(signable);
1 ✔
473

474
                if (detached) {
1 ✔
475
                    detach(signable, detachedSignature);
1 ✔
476
                }
477
            }
478

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

488
    private void attach(Signable signable, File detachedSignature) throws IOException {
489
        byte[] signatureBytes = Files.readAllBytes(detachedSignature.toPath());
1 ✔
490
        signable.setSignatures(SignatureUtils.getSignatures(signatureBytes));
1 ✔
491
        signable.save();
1 ✔
492
        // todo warn if the hashes don't match
493
    }
1 ✔
494

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

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

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

523
    private File getDetachedSignature(File file) {
524
        return new File(file.getParentFile(), file.getName() + ".sig");
1 ✔
525
    }
526

527
    private void extract(File file) throws SignerException {
528
        if (!file.exists()) {
1 ✔
529
            throw new SignerException("Couldn't find " + file);
1 ✔
530
        }
531

532
        try (Signable signable = Signable.of(file)) {
1 ✔
533
            List<CMSSignedData> signatures = signable.getSignatures();
1 ✔
534
            if (signatures.isEmpty()) {
1 ✔
535
                throw new SignerException("No signature found in " + file);
1 ✔
536
            }
537

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

553
    private void remove(File file) throws SignerException {
554
        if (!file.exists()) {
1 ✔
555
            throw new SignerException("Couldn't find " + file);
1 ✔
556
        }
557

558
        try (Signable signable = Signable.of(file)) {
1 ✔
559
            List<CMSSignedData> signatures = signable.getSignatures();
1 ✔
560
            if (signatures.isEmpty()) {
1 ✔
561
                log.severe("No signature found in " + file);
1 ✔
562
                return;
1 ✔
563
            }
564

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

575
    private void tag(File file) throws SignerException {
576
        if (!file.exists()) {
1 ✔
577
            throw new SignerException("Couldn't find " + file);
1 ✔
578
        }
579

580
        try (Signable signable = Signable.of(file)) {
1 ✔
581
            List<CMSSignedData> signatures = signable.getSignatures();
1 ✔
582
            if (signatures.isEmpty()) {
1 ✔
583
                throw new SignerException("No signature found in " + file);
1 ✔
584
            }
585

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

597
    private CMSSignedData addUnsignedAttribute(CMSSignedData signature, ASN1ObjectIdentifier oid, ASN1Encodable value) {
598
        SignerInformationStore store = signature.getSignerInfos();
1 ✔
599
        Collection<SignerInformation> signers = store.getSigners();
1 ✔
600
        SignerInformation signer = signers.iterator().next();
1 ✔
601

602
        AttributeTable attributes = signer.getUnsignedAttributes();
1 ✔
603
        if (attributes == null) {
1 ✔
604
            attributes = new AttributeTable(new DERSet());
1 ✔
605
        }
606
        attributes = attributes.add(oid, value);
1 ✔
607

608
        signers.remove(signer);
1 ✔
609
        signers.add(SignerInformation.replaceUnsignedAttributes(signer, attributes));
1 ✔
610
        return CMSSignedData.replaceSigners(signature, new SignerInformationStore(signers));
1 ✔
611
    }
612

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

622
        } else if (value.startsWith("0x")) {
1 ✔
623
            byte[] array = Hex.decode(value.substring(2));
1 ✔
624
            return new DEROctetString(array);
1 ✔
625

626
        } else if (value.startsWith("file:")) {
1 ✔
627
            byte[] array = Files.readAllBytes(new File(value.substring("file:".length())).toPath());
1 ✔
628
            return new DEROctetString(array);
1 ✔
629

630
        } else {
631
            return new DERUTF8String(value);
1 ✔
632
        }
633
    }
634

635
    private void timestamp(File file) throws SignerException {
636
        if (!file.exists()) {
1 ✔
637
            throw new SignerException("Couldn't find " + file);
1 ✔
638
        }
639

640
        try {
641
            initializeProxy(proxyUrl, proxyUser, proxyPass);
1 ✔
642
        } catch (Exception e) {
×
643
            throw new SignerException("Couldn't initialize proxy", e);
×
644
        }
1 ✔
645

646
        try (Signable signable = Signable.of(file)) {
1 ✔
647
            if (signable.getSignatures().isEmpty()) {
1 ✔
648
                throw new SignerException("No signature found in " + file);
1 ✔
649
            }
650

651
            Timestamper timestamper = Timestamper.create(tsmode != null ? TimestampingMode.of(tsmode) : TimestampingMode.AUTHENTICODE);
1 ✔
652
            timestamper.setRetries(tsretries);
1 ✔
653
            timestamper.setRetryWait(tsretrywait);
1 ✔
654
            if (tsaurl != null) {
1 ✔
655
                timestamper.setURLs(tsaurl.split(","));
1 ✔
656
            }
657
            DigestAlgorithm digestAlgorithm = alg != null ? DigestAlgorithm.of(alg) : DigestAlgorithm.getDefault();
1 ✔
658

659
            List<CMSSignedData> signatures = new ArrayList<>();
1 ✔
660
            for (CMSSignedData signature : signable.getSignatures()) {
1 ✔
661
                SignerInformation signerInformation = signature.getSignerInfos().iterator().next();
1 ✔
662
                SignerId signerId = signerInformation.getSID();
1 ✔
663
                X509CertificateHolder certificate = (X509CertificateHolder) signature.getCertificates().getMatches(signerId).iterator().next();
1 ✔
664

665
                String digestAlgorithmName = new DefaultAlgorithmNameFinder().getAlgorithmName(signerInformation.getDigestAlgorithmID()); 
1 ✔
666
                String keyAlgorithmName = new DefaultAlgorithmNameFinder().getAlgorithmName(new ASN1ObjectIdentifier(signerInformation.getEncryptionAlgOID()));
1 ✔
667
                String name = digestAlgorithmName + "/" + keyAlgorithmName + " signature from '" + certificate.getSubject() + "'";
1 ✔
668

669
                if (SignatureUtils.isTimestamped(signature) && !replace) {
1 ✔
670
                    log.fine(name + " already timestamped");
1 ✔
671
                    signatures.add(signature);
1 ✔
672
                    continue;
1 ✔
673
                }
674

675
                boolean expired = certificate.getNotAfter().before(new Date());
1 ✔
676
                if (expired) {
1 ✔
677
                    log.fine(name + " is expired, skipping");
×
678
                    signatures.add(signature);
×
679
                    continue;
×
680
                }
681

682
                log.info("Adding timestamp to " + name);
1 ✔
683
                signature = SignatureUtils.removeTimestamp(signature);
1 ✔
684
                signature = timestamper.timestamp(digestAlgorithm, signature);
1 ✔
685

686
                signatures.add(signature);
1 ✔
687
            }
1 ✔
688

689
            signable.setSignatures(signatures);
1 ✔
690
            signable.save();
1 ✔
691
        } catch (IOException | CMSException e) {
×
692
            throw new SignerException("Couldn't timestamp " + file, e);
×
693
        }
1 ✔
694
    }
1 ✔
695

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

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

724
                public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
725
                }
×
726
            });
727

728
            if (proxyUser != null && !proxyUser.isEmpty() && proxyPassword != null) {
1 ✔
729
                Authenticator.setDefault(new Authenticator() {
1 ✔
730
                    protected PasswordAuthentication getPasswordAuthentication() {
731
                        return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
1 ✔
732
                    }
733
                });
734
            }
735
        }
736
    }
1 ✔
737
}
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