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

ebourg / jsign / #362

12 Feb 2025 09:51AM UTC coverage: 83.503% (+0.03%) from 83.469%
#362

push

ebourg
Save the modified file after tagging/timestamping (Fixes #281)

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

3 existing lines in 1 file now uncovered.

4834 of 5789 relevant lines covered (83.5%)

0.84 hits per line

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

96.05
/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.LinkedHashMap;
28
import java.util.List;
29
import java.util.Map;
30
import java.util.logging.Level;
31
import java.util.logging.Logger;
32
import java.util.stream.Collectors;
33
import java.util.stream.Stream;
34

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

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

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

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

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

74
        Options options = new Options();
1✔
75
        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✔
76
        options.addOption(Option.builder().hasArg().longOpt(PARAM_STOREPASS).argName("PASSWORD").desc("The password to open the keystore").build());
1✔
77
        options.addOption(Option.builder().hasArg().longOpt(PARAM_STORETYPE).argName("TYPE")
1✔
78
                .desc("The type of the keystore\n"
1✔
79
                        + "File based:\n"
80
                        + "- JKS: Java keystore (.jks files)\n"
81
                        + "- JCEKS: SunJCE keystore (.jceks files)\n"
82
                        + "- PKCS12: Standard PKCS#12 keystore (.p12 or .pfx files)\n"
83
                        + "Hardware tokens\n"
84
                        + "- PKCS11: PKCS#11 hardware token\n"
85
                        + "- ETOKEN: SafeNet eToken\n"
86
                        + "- NITROKEY: Nitrokey HSM\n"
87
                        + "- OPENPGP: OpenPGP card\n"
88
                        + "- OPENSC: Smart card\n"
89
                        + "- PIV: PIV card\n"
90
                        + "- YUBIKEY: YubiKey security key\n"
91
                        + "Cloud key management systems:\n"
92
                        + "- AWS: AWS Key Management Service\n"
93
                        + "- AZUREKEYVAULT: Azure Key Vault key management system\n"
94
                        + "- DIGICERTONE: DigiCert ONE Secure Software Manager\n"
95
                        + "- ESIGNER: SSL.com eSigner\n"
96
                        + "- GARASIGN: Garantir Remote Signing\n"
97
                        + "- GOOGLECLOUD: Google Cloud KMS\n"
98
                        + "- HASHICORPVAULT: HashiCorp Vault\n"
99
                        + "- ORACLECLOUD: Oracle Cloud Key Management Service\n"
100
                        + "- SIGNPATH: SignPath\n"
101
                        + "- SIGNSERVER: Keyfactor SignServer\n"
102
                        + "- TRUSTEDSIGNING: Azure Trusted Signing\n").build());
1✔
103
        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✔
104
        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✔
105
        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✔
106
        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✔
107
        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✔
108
        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✔
109
        options.addOption(Option.builder("t").hasArg().longOpt(PARAM_TSAURL).argName("URL").desc("The URL of the timestamping authority").build());
1✔
110
        options.addOption(Option.builder("m").hasArg().longOpt(PARAM_TSMODE).argName("MODE").desc("The timestamping mode (RFC3161 or Authenticode)").build());
1✔
111
        options.addOption(Option.builder("r").hasArg().longOpt(PARAM_TSRETRIES).argName("NUMBER").desc("The number of retries for timestamping").build());
1✔
112
        options.addOption(Option.builder("w").hasArg().longOpt(PARAM_TSRETRY_WAIT).argName("SECONDS").desc("The number of seconds to wait between timestamping retries").build());
1✔
113
        options.addOption(Option.builder("n").hasArg().longOpt(PARAM_NAME).argName("NAME").desc("The name of the application").build());
1✔
114
        options.addOption(Option.builder("u").hasArg().longOpt(PARAM_URL).argName("URL").desc("The URL of the application").build());
1✔
115
        options.addOption(Option.builder().hasArg().longOpt(PARAM_PROXY_URL).argName("URL").desc("The URL of the HTTP proxy").build());
1✔
116
        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✔
117
        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✔
118
        options.addOption(Option.builder().longOpt(PARAM_REPLACE).desc("Tells if the previous signatures should be replaced").build());
1✔
119
        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✔
120
        options.addOption(Option.builder().longOpt(PARAM_DETACHED).desc("Tells if a detached signature should be generated or reused").build());
1✔
121
        options.addOption(Option.builder().longOpt("quiet").desc("Print only error messages").build());
1✔
122
        options.addOption(Option.builder().longOpt("verbose").desc("Print more information").build());
1✔
123
        options.addOption(Option.builder().longOpt("debug").desc("Print debugging information").build());
1✔
124
        options.addOption(Option.builder("h").longOpt("help").desc("Print the help").build());
1✔
125

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

128
        options = new Options();
1✔
129
        options.addOption(Option.builder("t").hasArg().longOpt(PARAM_TSAURL).argName("URL").desc("The URL of the timestamping authority").build());
1✔
130
        options.addOption(Option.builder("m").hasArg().longOpt(PARAM_TSMODE).argName("MODE").desc("The timestamping mode (RFC3161 or Authenticode)").build());
1✔
131
        options.addOption(Option.builder("r").hasArg().longOpt(PARAM_TSRETRIES).argName("NUMBER").desc("The number of retries for timestamping").build());
1✔
132
        options.addOption(Option.builder("w").hasArg().longOpt(PARAM_TSRETRY_WAIT).argName("SECONDS").desc("The number of seconds to wait between timestamping retries").build());
1✔
133
        options.addOption(Option.builder().hasArg().longOpt(PARAM_PROXY_URL).argName("URL").desc("The URL of the HTTP proxy").build());
1✔
134
        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✔
135
        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✔
136
        options.addOption(Option.builder().longOpt(PARAM_REPLACE).desc("Tells if the previous timestamps should be replaced").build());
1✔
137

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

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

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

145
        options = new Options();
1✔
146

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

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

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

154
        return map;
1✔
155
    }
156

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

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

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

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

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

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

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

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

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

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

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

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

274
    private void printHelp() {
275
        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✔
276
        String footer ="\n" +
1✔
277
                "Examples:\n\n" +
278
                "   Signing with a PKCS#12 keystore and timestamping:\n\n" +
279
                "     jsign --keystore keystore.p12 --alias test --storepass pwd \\\n" +
280
                "           --tsaurl http://timestamp.sectigo.com application.exe\n\n" +
281
                "   Signing with a SPC certificate and a PVK key:\n\n" +
282
                "     jsign --certfile certificate.spc --keyfile key.pvk --keypass pwd installer.msi\n\n" +
283
                "Please report suggestions and issues on the GitHub project at https://github.com/ebourg/jsign/issues";
284

285
        HelpFormatter formatter = new HelpFormatter();
1✔
286
        formatter.setOptionComparator(null);
1✔
287
        formatter.setWidth(85);
1✔
288
        formatter.setDescPadding(1);
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
        for (String command : options.keySet()) {
1✔
299
            if (!options.get(command).getOptions().isEmpty()) {
1✔
300
                out.println();
1✔
301
                out.println(command + ":");
1✔
302
                formatter.printOptions(out, formatter.getWidth(), options.get(command), formatter.getLeftPadding(), formatter.getDescPadding());
1✔
303
            }
304
        }
1✔
305
        formatter.printWrapped(out, formatter.getWidth(), footer);
1✔
306
        out.flush();
1✔
307
    }
1✔
308

309
    private static String getProgramName() {
310
        return System.getProperty("basename", "java -jar jsign.jar");
1✔
311
    }
312
}
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