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

ebourg / jsign / #382

02 Oct 2025 02:50PM UTC coverage: 83.308% (+0.08%) from 83.226%
#382

push

ebourg
Apply the proxy settings before accessing the cloud signing services (Fixes #324)

2 of 4 new or added lines in 1 file covered. (50.0%)

36 existing lines in 2 files now uncovered.

4951 of 5943 relevant lines covered (83.31%)

0.83 hits per line

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

96.13
/jsign-cli/src/main/java/net/jsign/JsignCLI.java
1
/*
2
 * Copyright 2012 Emmanuel Bourg
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package net.jsign;
18

19
import java.io.BufferedInputStream;
20
import java.io.File;
21
import java.io.FileInputStream;
22
import java.io.IOException;
23
import java.io.PrintWriter;
24
import java.nio.file.Path;
25
import java.util.Arrays;
26
import java.util.Collections;
27
import java.util.HashMap;
28
import java.util.LinkedHashMap;
29
import java.util.List;
30
import java.util.Map;
31
import java.util.logging.Level;
32
import java.util.logging.Logger;
33
import java.util.stream.Collectors;
34
import java.util.stream.Stream;
35

36
import org.apache.commons.cli.CommandLine;
37
import org.apache.commons.cli.DefaultParser;
38
import org.apache.commons.cli.HelpFormatter;
39
import org.apache.commons.cli.Option;
40
import org.apache.commons.cli.Options;
41
import org.apache.commons.cli.ParseException;
42
import org.apache.commons.io.IOUtils;
43
import org.apache.commons.io.input.BOMInputStream;
44

45
import static net.jsign.SignerHelper.*;
46
import static org.apache.commons.io.ByteOrderMark.*;
47

48
/**
49
 * Command line interface for signing files.
50
 *
51
 * @author Emmanuel Bourg
52
 * @since 1.1
53
 */
54
public class JsignCLI {
1✔
55

56
    public static void main(String... args) {
57
        try {
58
            new JsignCLI().execute(args);
1✔
59
        } catch (SignerException | IllegalArgumentException | ParseException e) {
1✔
60
            System.err.println("jsign: " + e.getMessage());
1✔
61
            if (e.getCause() != null) {
1✔
UNCOV
62
                e.getCause().printStackTrace(System.err);
×
63
            }
64
            System.err.println("Try `" + getProgramName() + " --help' for more information.");
1✔
UNCOV
65
            System.exit(1);
×
66
        }
1✔
67
    }
1✔
68

69
    /**
70
     * Returns the options for each operation.
71
     */
72
    private Map<String, Options> getOptions() {
73
        Map<String, Options> map = new LinkedHashMap<>();
1✔
74

75
        Options options = new Options();
1✔
76
        options.addOption(Option.builder("s").hasArg().longOpt(PARAM_KEYSTORE).argName("FILE").desc("The keystore file, the SunPKCS11 configuration file, the cloud keystore name, or the card/token name").type(File.class).build());
1✔
77
        options.addOption(Option.builder().hasArg().longOpt(PARAM_STOREPASS).argName("PASSWORD").desc("The password to open the keystore").build());
1✔
78
        options.addOption(Option.builder().hasArg().longOpt(PARAM_STORETYPE).argName("TYPE")
1✔
79
                .desc("The type of the keystore\n"
1✔
80
                        + "File based:\n"
81
                        + "- JKS: Java keystore (.jks files)\n"
82
                        + "- JCEKS: SunJCE keystore (.jceks files)\n"
83
                        + "- PKCS12: Standard PKCS#12 keystore (.p12 or .pfx files)\n"
84
                        + "Hardware tokens\n"
85
                        + "- PKCS11: PKCS#11 hardware token\n"
86
                        + "- ETOKEN: SafeNet eToken\n"
87
                        + "- NITROKEY: Nitrokey HSM\n"
88
                        + "- OPENPGP: OpenPGP card\n"
89
                        + "- OPENSC: Smart card\n"
90
                        + "- PIV: PIV card\n"
91
                        + "- YUBIKEY: YubiKey security key\n"
92
                        + "Cloud key management systems:\n"
93
                        + "- AWS: AWS Key Management Service\n"
94
                        + "- AZUREKEYVAULT: Azure Key Vault key management system\n"
95
                        + "- DIGICERTONE: DigiCert ONE Secure Software Manager\n"
96
                        + "- ESIGNER: SSL.com eSigner\n"
97
                        + "- GARASIGN: Garantir Remote Signing\n"
98
                        + "- GOOGLECLOUD: Google Cloud KMS\n"
99
                        + "- HASHICORPVAULT: HashiCorp Vault\n"
100
                        + "- ORACLECLOUD: Oracle Cloud Key Management Service\n"
101
                        + "- SIGNPATH: SignPath\n"
102
                        + "- SIGNSERVER: Keyfactor SignServer\n"
103
                        + "- TRUSTEDSIGNING: Azure Trusted Signing\n").build());
1✔
104
        options.addOption(Option.builder("a").hasArg().longOpt(PARAM_ALIAS).argName("NAME").desc("The alias of the certificate used for signing in the keystore").build());
1✔
105
        options.addOption(Option.builder().hasArg().longOpt(PARAM_KEYPASS).argName("PASSWORD").desc("The password of the private key. When using a keystore, this parameter can be omitted if the keystore shares the same password").build());
1✔
106
        options.addOption(Option.builder().hasArg().longOpt(PARAM_KEYFILE).argName("FILE").desc("The file containing the private key. PEM and PVK files are supported").type(File.class).build());
1✔
107
        options.addOption(Option.builder("c").hasArg().longOpt(PARAM_CERTFILE).argName("FILE").desc("The file containing the PKCS#7 certificate chain\n(.p7b or .spc files)").type(File.class).build());
1✔
108
        options.addOption(Option.builder("d").hasArg().longOpt(PARAM_ALG).argName("ALGORITHM").desc("The digest algorithm (SHA-1, SHA-256, SHA-384 or SHA-512)").build());
1✔
109
        options.addOption(Option.builder("t").hasArg().longOpt(PARAM_TSAURL).argName("URL").desc("The URL of the timestamping authority. Several URLs separated by a comma can be specified to fallback on alternative servers").build());
1✔
110
        options.addOption(Option.builder("t").hasArg().longOpt(PARAM_TSAURL).argName("URL").desc("The URL of the timestamping authority").build());
1✔
111
        options.addOption(Option.builder("m").hasArg().longOpt(PARAM_TSMODE).argName("MODE").desc("The timestamping mode (RFC3161 or Authenticode)").build());
1✔
112
        options.addOption(Option.builder("r").hasArg().longOpt(PARAM_TSRETRIES).argName("NUMBER").desc("The number of retries for timestamping").build());
1✔
113
        options.addOption(Option.builder("w").hasArg().longOpt(PARAM_TSRETRY_WAIT).argName("SECONDS").desc("The number of seconds to wait between timestamping retries").build());
1✔
114
        options.addOption(Option.builder("n").hasArg().longOpt(PARAM_NAME).argName("NAME").desc("The name of the application").build());
1✔
115
        options.addOption(Option.builder("u").hasArg().longOpt(PARAM_URL).argName("URL").desc("The URL of the application").build());
1✔
116
        options.addOption(Option.builder().hasArg().longOpt(PARAM_PROXY_URL).argName("URL").desc("The URL of the HTTP proxy").build());
1✔
117
        options.addOption(Option.builder().hasArg().longOpt(PARAM_PROXY_USER).argName("NAME").desc("The user for the HTTP proxy. If a user is needed").build());
1✔
118
        options.addOption(Option.builder().hasArg().longOpt(PARAM_PROXY_PASS).argName("PASSWORD").desc("The password for the HTTP proxy user. If a user is needed").build());
1✔
119
        options.addOption(Option.builder().longOpt(PARAM_REPLACE).desc("Tells if the previous signatures should be replaced").build());
1✔
120
        options.addOption(Option.builder("e").hasArg().longOpt(PARAM_ENCODING).argName("ENCODING").desc("The encoding of the script to be signed (UTF-8 by default, or the encoding specified by the byte order mark if there is one)").build());
1✔
121
        options.addOption(Option.builder().longOpt(PARAM_DETACHED).desc("Tells if a detached signature should be generated or reused").build());
1✔
122
        options.addOption(Option.builder().longOpt("quiet").desc("Print only error messages").build());
1✔
123
        options.addOption(Option.builder().longOpt("verbose").desc("Print more information").build());
1✔
124
        options.addOption(Option.builder().longOpt("debug").desc("Print debugging information").build());
1✔
125
        options.addOption(Option.builder("h").longOpt("help").desc("Print the help").build());
1✔
126

127
        map.put("sign", options);
1✔
128

129
        options = new Options();
1✔
130
        options.addOption(Option.builder("t").hasArg().longOpt(PARAM_TSAURL).argName("URL").desc("The URL of the timestamping authority").build());
1✔
131
        options.addOption(Option.builder("m").hasArg().longOpt(PARAM_TSMODE).argName("MODE").desc("The timestamping mode (RFC3161 or Authenticode)").build());
1✔
132
        options.addOption(Option.builder("r").hasArg().longOpt(PARAM_TSRETRIES).argName("NUMBER").desc("The number of retries for timestamping").build());
1✔
133
        options.addOption(Option.builder("w").hasArg().longOpt(PARAM_TSRETRY_WAIT).argName("SECONDS").desc("The number of seconds to wait between timestamping retries").build());
1✔
134
        options.addOption(Option.builder().hasArg().longOpt(PARAM_PROXY_URL).argName("URL").desc("The URL of the HTTP proxy").build());
1✔
135
        options.addOption(Option.builder().hasArg().longOpt(PARAM_PROXY_USER).argName("NAME").desc("The user for the HTTP proxy. If a user is needed").build());
1✔
136
        options.addOption(Option.builder().hasArg().longOpt(PARAM_PROXY_PASS).argName("PASSWORD").desc("The password for the HTTP proxy user. If a user is needed").build());
1✔
137
        options.addOption(Option.builder().longOpt(PARAM_REPLACE).desc("Tells if the previous timestamps should be replaced").build());
1✔
138

139
        map.put("timestamp", options);
1✔
140

141
        options = new Options();
1✔
142
        options.addOption(Option.builder().hasArg().longOpt(PARAM_FORMAT).argName("FORMAT").desc("The output format of the signature (DER or PEM)").build());
1✔
143

144
        map.put("extract", options);
1✔
145

146
        options = new Options();
1✔
147

148
        map.put("remove", options);
1✔
149

150
        options = new Options();
1✔
151
        options.addOption(Option.builder().hasArg().longOpt(PARAM_VALUE).argName("VALUE").desc("The value of the unsigned attribute").build());
1✔
152

153
        map.put("tag", options);
1✔
154

155
        return map;
1✔
156
    }
157

158
    void execute(String... args) throws SignerException, ParseException {
159
        DefaultParser parser = new DefaultParser();
1✔
160
        
161
        String command = "sign";
1✔
162
        if (args.length >= 1 && !args[0].startsWith("-")) {
1✔
163
            command = args[0];
1✔
164
            args = Arrays.copyOfRange(args, 1, args.length);
1✔
165
        }
166

167
        Options options = getOptions().get(command);
1✔
168
        if (options == null) {
1✔
169
            throw new ParseException("Unknown command '" + command + "'");
1✔
170
        }
171
        options.addOption(Option.builder().longOpt("quiet").build());
1✔
172
        options.addOption(Option.builder().longOpt("verbose").build());
1✔
173
        options.addOption(Option.builder().longOpt("debug").build());
1✔
174

175
        CommandLine cmd = parser.parse(options, args);
1✔
176

177
        if (cmd.hasOption("help") || args.length == 0) {
1✔
178
            printHelp();
1✔
179
            return;
1✔
180
        }
181

182
        // configure the logging
183
        Logger log = Logger.getLogger("net.jsign");
1✔
184
        log.setLevel(cmd.hasOption("debug") ? Level.FINEST : cmd.hasOption("verbose") ? Level.FINE : cmd.hasOption("quiet") ? Level.WARNING : Level.INFO);
1✔
185
        log.setUseParentHandlers(false);
1✔
186
        Stream.of(log.getHandlers()).forEach(log::removeHandler);
1✔
187
        log.addHandler(new StdOutLogHandler());
1✔
188

189
        SignerHelper helper = new SignerHelper("option");
1✔
190
        helper.command(command);
1✔
191
        
192
        setOption(PARAM_KEYSTORE, helper, cmd);
1✔
193
        setOption(PARAM_STOREPASS, helper, cmd);
1✔
194
        setOption(PARAM_STORETYPE, helper, cmd);
1✔
195
        setOption(PARAM_ALIAS, helper, cmd);
1✔
196
        setOption(PARAM_KEYPASS, helper, cmd);
1✔
197
        setOption(PARAM_KEYFILE, helper, cmd);
1✔
198
        setOption(PARAM_CERTFILE, helper, cmd);
1✔
199
        setOption(PARAM_ALG, helper, cmd);
1✔
200
        setOption(PARAM_TSAURL, helper, cmd);
1✔
201
        setOption(PARAM_TSMODE, helper, cmd);
1✔
202
        setOption(PARAM_TSRETRIES, helper, cmd);
1✔
203
        setOption(PARAM_TSRETRY_WAIT, helper, cmd);
1✔
204
        setOption(PARAM_NAME, helper, cmd);
1✔
205
        setOption(PARAM_URL, helper, cmd);
1✔
206
        setOption(PARAM_PROXY_URL, helper, cmd);
1✔
207
        setOption(PARAM_PROXY_USER, helper, cmd);
1✔
208
        setOption(PARAM_PROXY_PASS, helper, cmd);
1✔
209
        helper.replace(cmd.hasOption(PARAM_REPLACE));
1✔
210
        setOption(PARAM_ENCODING, helper, cmd);
1✔
211
        helper.detached(cmd.hasOption(PARAM_DETACHED));
1✔
212
        setOption(PARAM_FORMAT, helper, cmd);
1✔
213
        setOption(PARAM_VALUE, helper, cmd);
1✔
214

215
        if (cmd.getArgList().isEmpty()) {
1✔
216
            throw new SignerException("No file specified");
1✔
217
        }
218

219
        for (String arg : cmd.getArgList()) {
1✔
220
            for (String filename : expand(arg)) {
1✔
221
                if (!filename.trim().isEmpty() && !filename.startsWith("#")) {
1✔
222
                    helper.execute(new File(unquote(filename)));
1✔
223
                }
224
            }
1✔
225
        }
1✔
226
    }
1✔
227

228
    /**
229
     * Expands filenames starting with @ to a list of filenames.
230
     */
231
    private List<String> expand(String filename) {
232
        if (filename.startsWith("@")) {
1✔
233
            try {
234
                return readFile(new File(filename.substring(1)));
1✔
235
            } catch (IOException e) {
×
UNCOV
236
                throw new IllegalArgumentException("Failed to read the file list: " + filename.substring(1), e);
×
237
            }
238
        } else if (filename.contains("*")) {
1✔
239
            try {
240
                return new DirectoryScanner().scan(filename).stream().map(Path::toString).collect(Collectors.toList());
1✔
241
            } catch (IOException e) {
×
UNCOV
242
                throw new IllegalArgumentException("Failed to scan the directory: " + filename, e);
×
243
            }
244
        } else {
245
            return Collections.singletonList(filename);
1✔
246
        }
247
    }
248

249
    /**
250
     * Reads the content of the text file specified. Byte order marks are supported to detect the encoding,
251
     * otherwise UTF-8 is used.
252
     */
253
    private List<String> readFile(File file) throws IOException {
254
        try (BOMInputStream in = new BOMInputStream(new BufferedInputStream(new FileInputStream(file)), false, UTF_8, UTF_16BE, UTF_16LE)) {
1✔
255
            return IOUtils.readLines(in, in.hasBOM() ? in.getBOMCharsetName() : "UTF-8");
1✔
256
        }
257
    }
258

259
    /**
260
     * Removes the quotes around the specified file name.
261
     */
262
    private String unquote(String value) {
263
        value = value.trim();
1✔
264
        if (value.startsWith("\"") && value.endsWith("\"")) {
1✔
265
            value = value.substring(1, value.length() - 1);
1✔
266
        }
267
        return value;
1✔
268
    }
269

270
    private void setOption(String key, SignerHelper helper, CommandLine cmd) {
271
        String value = cmd.getOptionValue(key);
1✔
272
        helper.param(key, value);
1✔
273
    }
1✔
274

275
    private void printHelp() {
276
        String header = "Sign and timestamp Windows executable files, Microsoft Installers (MSI), Cabinet files (CAB), Catalog files (CAT), Windows packages (APPX/MSIX), Microsoft Dynamics 365 extension packages, NuGet packages and scripts (PowerShell, VBScript, JScript, WSF)\n\n";
1✔
277
        String footer ="\n" +
1✔
278
                "Examples:\n\n" +
279
                "   Signing with a PKCS#12 keystore and timestamping:\n\n" +
280
                "     jsign --keystore keystore.p12 --alias test --storepass pwd \\\n" +
281
                "           --tsaurl http://timestamp.sectigo.com application.exe\n\n" +
282
                "   Signing with a SPC certificate and a PVK key:\n\n" +
283
                "     jsign --certfile certificate.spc --keyfile key.pvk --keypass pwd installer.msi\n\n" +
284
                "Please report suggestions and issues on the GitHub project at https://github.com/ebourg/jsign/issues";
285

286
        HelpFormatter formatter = new HelpFormatter();
1✔
287
        formatter.setOptionComparator(null);
1✔
288
        formatter.setWidth(85);
1✔
289

290
        PrintWriter out = new PrintWriter(System.out);
1✔
291
        formatter.printUsage(out, formatter.getWidth(), getProgramName() + " [COMMAND] [OPTIONS] [FILE] [PATTERN] [@FILELIST]...");
1✔
292
        out.println();
1✔
293
        formatter.printWrapped(out, formatter.getWidth(), header);
1✔
294

295
        Map<String, Options> options = getOptions();
1✔
296
        out.println("commands: " + options.keySet().stream().map(s -> "sign".equals(s) ? s + " (default)" : s).collect(Collectors.joining(", ")));
1✔
297

298
        Map<String, Integer> paddings = new HashMap<>();
1✔
299
        paddings.put("extract", 6);
1✔
300
        paddings.put("tag", 8);
1✔
301

302
        for (String command : options.keySet()) {
1✔
303
            if (!options.get(command).getOptions().isEmpty()) {
1✔
304
                out.println();
1✔
305
                out.println(command + ":");
1✔
306
                formatter.setDescPadding(paddings.getOrDefault(command, 1));
1✔
307
                formatter.printOptions(out, formatter.getWidth(), options.get(command), formatter.getLeftPadding(), formatter.getDescPadding());
1✔
308
            }
309
        }
1✔
310
        formatter.printWrapped(out, formatter.getWidth(), footer);
1✔
311
        out.flush();
1✔
312
    }
1✔
313

314
    private static String getProgramName() {
315
        return System.getProperty("basename", "java -jar jsign.jar");
1✔
316
    }
317
}
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