Main.java 182.2 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25
 */

26
package sun.security.tools.keytool;
D
duke 已提交
27 28

import java.io.*;
29 30
import java.nio.file.Files;
import java.nio.file.Paths;
31
import java.security.CodeSigner;
32
import java.security.CryptoPrimitive;
D
duke 已提交
33 34 35 36 37 38 39 40
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.Key;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.Security;
import java.security.Signature;
41
import java.security.Timestamp;
D
duke 已提交
42 43
import java.security.UnrecoverableEntryException;
import java.security.UnrecoverableKeyException;
44
import java.security.NoSuchAlgorithmException;
D
duke 已提交
45 46 47 48
import java.security.Principal;
import java.security.Provider;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
49
import java.security.cert.CertStoreException;
50
import java.security.cert.CRL;
D
duke 已提交
51 52
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
53
import java.security.spec.AlgorithmParameterSpec;
D
duke 已提交
54 55 56
import java.text.Collator;
import java.text.MessageFormat;
import java.util.*;
57 58
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
D
duke 已提交
59
import java.lang.reflect.Constructor;
60 61
import java.math.BigInteger;
import java.net.URI;
D
duke 已提交
62 63
import java.net.URL;
import java.net.URLClassLoader;
64
import java.security.cert.CertStore;
D
duke 已提交
65

66 67 68 69
import java.security.cert.X509CRL;
import java.security.cert.X509CRLEntry;
import java.security.cert.X509CRLSelector;
import javax.security.auth.x500.X500Principal;
70
import java.util.Base64;
71

72
import sun.security.util.DisabledAlgorithmConstraints;
73
import sun.security.util.KeyUtil;
D
duke 已提交
74
import sun.security.util.ObjectIdentifier;
75 76
import sun.security.pkcs10.PKCS10;
import sun.security.pkcs10.PKCS10Attribute;
D
duke 已提交
77
import sun.security.provider.X509Factory;
78
import sun.security.provider.certpath.CertStoreHelper;
D
duke 已提交
79
import sun.security.util.Password;
80
import sun.security.util.SecurityProviderConstants;
81
import sun.security.util.SignatureUtil;
D
duke 已提交
82 83
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
84 85
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
D
duke 已提交
86

87
import sun.security.pkcs.PKCS9Attribute;
88 89
import sun.security.tools.KeyStoreUtil;
import sun.security.tools.PathList;
90
import sun.security.util.DerValue;
91
import sun.security.util.Pem;
D
duke 已提交
92 93 94
import sun.security.x509.*;

import static java.security.KeyStore.*;
95 96
import static sun.security.tools.keytool.Main.Command.*;
import static sun.security.tools.keytool.Main.Option.*;
D
duke 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109

/**
 * This tool manages keystores.
 *
 * @author Jan Luehe
 *
 *
 * @see java.security.KeyStore
 * @see sun.security.provider.KeyProtector
 * @see sun.security.provider.JavaKeyStore
 *
 * @since 1.2
 */
110
public final class Main {
D
duke 已提交
111

112 113
    private static final byte[] CRLF = new byte[] {'\r', '\n'};

D
duke 已提交
114
    private boolean debug = false;
W
weijun 已提交
115
    private Command command = null;
D
duke 已提交
116 117 118 119 120 121 122 123 124 125
    private String sigAlgName = null;
    private String keyAlgName = null;
    private boolean verbose = false;
    private int keysize = -1;
    private boolean rfc = false;
    private long validity = (long)90;
    private String alias = null;
    private String dname = null;
    private String dest = null;
    private String filename = null;
126 127
    private String infilename = null;
    private String outfilename = null;
D
duke 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    private String srcksfname = null;

    // User-specified providers are added before any command is called.
    // However, they are not removed before the end of the main() method.
    // If you're calling KeyTool.main() directly in your own Java program,
    // please programtically add any providers you need and do not specify
    // them through the command line.

    private Set<Pair <String, String>> providers = null;
    private String storetype = null;
    private String srcProviderName = null;
    private String providerName = null;
    private String pathlist = null;
    private char[] storePass = null;
    private char[] storePassNew = null;
    private char[] keyPass = null;
    private char[] keyPassNew = null;
    private char[] newPass = null;
    private char[] destKeyPass = null;
    private char[] srckeyPass = null;
    private String ksfname = null;
    private File ksfile = null;
    private InputStream ksStream = null; // keystore stream
151
    private String sslserver = null;
152
    private String jarfile = null;
D
duke 已提交
153 154 155 156 157 158
    private KeyStore keyStore = null;
    private boolean token = false;
    private boolean nullStream = false;
    private boolean kssave = false;
    private boolean noprompt = false;
    private boolean trustcacerts = false;
159
    private boolean nowarn = false;
D
duke 已提交
160 161 162 163 164 165
    private boolean protectedPath = false;
    private boolean srcprotectedPath = false;
    private CertificateFactory cf = null;
    private KeyStore caks = null; // "cacerts" keystore
    private char[] srcstorePass = null;
    private String srcstoretype = null;
166
    private Set<char[]> passwords = new HashSet<>();
D
duke 已提交
167 168
    private String startDate = null;

169 170
    private List<String> ids = new ArrayList<>();   // used in GENCRL
    private List<String> v3ext = new ArrayList<>();
171

172 173 174 175 176 177
    // In-place importkeystore is special.
    // A backup is needed, and no need to prompt for deststorepass.
    private boolean inplaceImport = false;
    private String inplaceBackupName = null;

    // Warnings on weak algorithms etc
178 179 180 181 182 183 184 185 186
    private List<String> weakWarnings = new ArrayList<>();

    private static final DisabledAlgorithmConstraints DISABLED_CHECK =
            new DisabledAlgorithmConstraints(
                    DisabledAlgorithmConstraints.PROPERTY_CERTPATH_DISABLED_ALGS);

    private static final Set<CryptoPrimitive> SIG_PRIMITIVE_SET = Collections
            .unmodifiableSet(EnumSet.of(CryptoPrimitive.SIGNATURE));

W
weijun 已提交
187
    enum Command {
188
        CERTREQ("Generates.a.certificate.request",
189
            ALIAS, SIGALG, FILEOUT, KEYPASS, KEYSTORE, DNAME,
190 191
            STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS,
            PROVIDERARG, PROVIDERPATH, V, PROTECTED),
192
        CHANGEALIAS("Changes.an.entry.s.alias",
193 194 195
            ALIAS, DESTALIAS, KEYPASS, KEYSTORE, STOREPASS,
            STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG,
            PROVIDERPATH, V, PROTECTED),
196
        DELETE("Deletes.an.entry",
197 198 199
            ALIAS, KEYSTORE, STOREPASS, STORETYPE,
            PROVIDERNAME, PROVIDERCLASS, PROVIDERARG,
            PROVIDERPATH, V, PROTECTED),
200
        EXPORTCERT("Exports.certificate",
201 202 203
            RFC, ALIAS, FILEOUT, KEYSTORE, STOREPASS,
            STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG,
            PROVIDERPATH, V, PROTECTED),
204
        GENKEYPAIR("Generates.a.key.pair",
205
            ALIAS, KEYALG, KEYSIZE, SIGALG, DESTALIAS, DNAME,
206 207 208
            STARTDATE, EXT, VALIDITY, KEYPASS, KEYSTORE,
            STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS,
            PROVIDERARG, PROVIDERPATH, V, PROTECTED),
209
        GENSECKEY("Generates.a.secret.key",
210 211 212
            ALIAS, KEYPASS, KEYALG, KEYSIZE, KEYSTORE,
            STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS,
            PROVIDERARG, PROVIDERPATH, V, PROTECTED),
213
        GENCERT("Generates.certificate.from.a.certificate.request",
214
            RFC, INFILE, OUTFILE, ALIAS, SIGALG, DNAME,
215 216 217
            STARTDATE, EXT, VALIDITY, KEYPASS, KEYSTORE,
            STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS,
            PROVIDERARG, PROVIDERPATH, V, PROTECTED),
218
        IMPORTCERT("Imports.a.certificate.or.a.certificate.chain",
219 220 221 222
            NOPROMPT, TRUSTCACERTS, PROTECTED, ALIAS, FILEIN,
            KEYPASS, KEYSTORE, STOREPASS, STORETYPE,
            PROVIDERNAME, PROVIDERCLASS, PROVIDERARG,
            PROVIDERPATH, V),
223 224 225 226
        IMPORTPASS("Imports.a.password",
            ALIAS, KEYPASS, KEYALG, KEYSIZE, KEYSTORE,
            STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS,
            PROVIDERARG, PROVIDERPATH, V, PROTECTED),
227
        IMPORTKEYSTORE("Imports.one.or.all.entries.from.another.keystore",
228 229 230 231 232 233
            SRCKEYSTORE, DESTKEYSTORE, SRCSTORETYPE,
            DESTSTORETYPE, SRCSTOREPASS, DESTSTOREPASS,
            SRCPROTECTED, SRCPROVIDERNAME, DESTPROVIDERNAME,
            SRCALIAS, DESTALIAS, SRCKEYPASS, DESTKEYPASS,
            NOPROMPT, PROVIDERCLASS, PROVIDERARG, PROVIDERPATH,
            V),
234
        KEYPASSWD("Changes.the.key.password.of.an.entry",
235 236 237
            ALIAS, KEYPASS, NEW, KEYSTORE, STOREPASS,
            STORETYPE, PROVIDERNAME, PROVIDERCLASS, PROVIDERARG,
            PROVIDERPATH, V),
238
        LIST("Lists.entries.in.a.keystore",
239 240 241
            RFC, ALIAS, KEYSTORE, STOREPASS, STORETYPE,
            PROVIDERNAME, PROVIDERCLASS, PROVIDERARG,
            PROVIDERPATH, V, PROTECTED),
242
        PRINTCERT("Prints.the.content.of.a.certificate",
243
            RFC, FILEIN, SSLSERVER, JARFILE, V),
244
        PRINTCERTREQ("Prints.the.content.of.a.certificate.request",
245
            FILEIN, V),
246
        PRINTCRL("Prints.the.content.of.a.CRL.file",
247
            FILEIN, V),
248
        STOREPASSWD("Changes.the.store.password.of.a.keystore",
249 250 251 252 253
            NEW, KEYSTORE, STOREPASS, STORETYPE, PROVIDERNAME,
            PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V),

        // Undocumented start here, KEYCLONE is used a marker in -help;

254
        KEYCLONE("Clones.a.key.entry",
255 256 257
            ALIAS, DESTALIAS, KEYPASS, NEW, STORETYPE,
            KEYSTORE, STOREPASS, PROVIDERNAME, PROVIDERCLASS,
            PROVIDERARG, PROVIDERPATH, V),
258
        SELFCERT("Generates.a.self.signed.certificate",
259 260 261
            ALIAS, SIGALG, DNAME, STARTDATE, VALIDITY, KEYPASS,
            STORETYPE, KEYSTORE, STOREPASS, PROVIDERNAME,
            PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V),
262
        GENCRL("Generates.CRL",
263 264 265 266
            RFC, FILEOUT, ID,
            ALIAS, SIGALG, EXT, KEYPASS, KEYSTORE,
            STOREPASS, STORETYPE, PROVIDERNAME, PROVIDERCLASS,
            PROVIDERARG, PROVIDERPATH, V, PROTECTED),
267
        IDENTITYDB("Imports.entries.from.a.JDK.1.1.x.style.identity.database",
268
            FILEIN, STORETYPE, KEYSTORE, STOREPASS, PROVIDERNAME,
269
            PROVIDERCLASS, PROVIDERARG, PROVIDERPATH, V);
W
weijun 已提交
270 271

        final String description;
272 273
        final Option[] options;
        Command(String d, Option... o) {
W
weijun 已提交
274 275 276 277 278 279 280 281 282
            description = d;
            options = o;
        }
        @Override
        public String toString() {
            return "-" + name().toLowerCase(Locale.ENGLISH);
        }
    };

283
    enum Option {
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
        ALIAS("alias", "<alias>", "alias.name.of.the.entry.to.process"),
        DESTALIAS("destalias", "<destalias>", "destination.alias"),
        DESTKEYPASS("destkeypass", "<arg>", "destination.key.password"),
        DESTKEYSTORE("destkeystore", "<destkeystore>", "destination.keystore.name"),
        DESTPROTECTED("destprotected", null, "destination.keystore.password.protected"),
        DESTPROVIDERNAME("destprovidername", "<destprovidername>", "destination.keystore.provider.name"),
        DESTSTOREPASS("deststorepass", "<arg>", "destination.keystore.password"),
        DESTSTORETYPE("deststoretype", "<deststoretype>", "destination.keystore.type"),
        DNAME("dname", "<dname>", "distinguished.name"),
        EXT("ext", "<value>", "X.509.extension"),
        FILEOUT("file", "<filename>", "output.file.name"),
        FILEIN("file", "<filename>", "input.file.name"),
        ID("id", "<id:reason>", "Serial.ID.of.cert.to.revoke"),
        INFILE("infile", "<filename>", "input.file.name"),
        KEYALG("keyalg", "<keyalg>", "key.algorithm.name"),
        KEYPASS("keypass", "<arg>", "key.password"),
        KEYSIZE("keysize", "<keysize>", "key.bit.size"),
        KEYSTORE("keystore", "<keystore>", "keystore.name"),
        NEW("new", "<arg>", "new.password"),
        NOPROMPT("noprompt", null, "do.not.prompt"),
        OUTFILE("outfile", "<filename>", "output.file.name"),
        PROTECTED("protected", null, "password.through.protected.mechanism"),
        PROVIDERARG("providerarg", "<arg>", "provider.argument"),
        PROVIDERCLASS("providerclass", "<providerclass>", "provider.class.name"),
        PROVIDERNAME("providername", "<providername>", "provider.name"),
        PROVIDERPATH("providerpath", "<pathlist>", "provider.classpath"),
        RFC("rfc", null, "output.in.RFC.style"),
        SIGALG("sigalg", "<sigalg>", "signature.algorithm.name"),
        SRCALIAS("srcalias", "<srcalias>", "source.alias"),
        SRCKEYPASS("srckeypass", "<arg>", "source.key.password"),
        SRCKEYSTORE("srckeystore", "<srckeystore>", "source.keystore.name"),
        SRCPROTECTED("srcprotected", null, "source.keystore.password.protected"),
        SRCPROVIDERNAME("srcprovidername", "<srcprovidername>", "source.keystore.provider.name"),
        SRCSTOREPASS("srcstorepass", "<arg>", "source.keystore.password"),
        SRCSTORETYPE("srcstoretype", "<srcstoretype>", "source.keystore.type"),
        SSLSERVER("sslserver", "<server[:port]>", "SSL.server.host.and.port"),
        JARFILE("jarfile", "<filename>", "signed.jar.file"),
        STARTDATE("startdate", "<startdate>", "certificate.validity.start.date.time"),
        STOREPASS("storepass", "<arg>", "keystore.password"),
        STORETYPE("storetype", "<storetype>", "keystore.type"),
        TRUSTCACERTS("trustcacerts", null, "trust.certificates.from.cacerts"),
        V("v", null, "verbose.output"),
        VALIDITY("validity", "<valDays>", "validity.number.of.days");
327 328 329 330 331 332 333 334 335 336 337

        final String name, arg, description;
        Option(String name, String arg, String description) {
            this.name = name;
            this.arg = arg;
            this.description = description;
        }
        @Override
        public String toString() {
            return "-" + name;
        }
W
weijun 已提交
338
    };
D
duke 已提交
339

340
    private static final Class<?>[] PARAM_STRING = { String.class };
D
duke 已提交
341 342 343 344

    private static final String NONE = "NONE";
    private static final String P11KEYSTORE = "PKCS11";
    private static final String P12KEYSTORE = "PKCS12";
345
    private static final String keyAlias = "mykey";
D
duke 已提交
346 347 348

    // for i18n
    private static final java.util.ResourceBundle rb =
349 350
        java.util.ResourceBundle.getBundle(
            "sun.security.tools.keytool.Resources");
D
duke 已提交
351 352 353 354 355 356
    private static final Collator collator = Collator.getInstance();
    static {
        // this is for case insensitive string comparisons
        collator.setStrength(Collator.PRIMARY);
    };

357
    private Main() { }
D
duke 已提交
358 359

    public static void main(String[] args) throws Exception {
360
        Main kt = new Main();
D
duke 已提交
361 362 363 364 365 366
        kt.run(args, System.out);
    }

    private void run(String[] args, PrintStream out) throws Exception {
        try {
            parseArgs(args);
W
weijun 已提交
367
            if (command != null) {
368 369
                doCommands(out);
            }
D
duke 已提交
370
        } catch (Exception e) {
371
            System.out.println(rb.getString("keytool.error.") + e);
D
duke 已提交
372 373 374 375 376 377 378 379 380
            if (verbose) {
                e.printStackTrace(System.out);
            }
            if (!debug) {
                System.exit(1);
            } else {
                throw e;
            }
        } finally {
381
            printWeakWarnings(false);
D
duke 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
            for (char[] pass : passwords) {
                if (pass != null) {
                    Arrays.fill(pass, ' ');
                    pass = null;
                }
            }

            if (ksStream != null) {
                ksStream.close();
            }
        }
    }

    /**
     * Parse command line arguments.
     */
    void parseArgs(String[] args) {

        int i=0;
W
weijun 已提交
401
        boolean help = args.length == 0;
D
duke 已提交
402 403 404 405

        for (i=0; (i < args.length) && args[i].startsWith("-"); i++) {

            String flags = args[i];
W
weijun 已提交
406 407 408

            // Check if the last option needs an arg
            if (i == args.length - 1) {
409
                for (Option option: Option.values()) {
W
weijun 已提交
410
                    // Only options with an arg need to be checked
411 412
                    if (collator.compare(flags, option.toString()) == 0) {
                        if (option.arg != null) errorNeedArgument(flags);
W
weijun 已提交
413 414 415 416 417
                        break;
                    }
                }
            }

418 419 420 421 422 423 424 425 426
            /*
             * Check modifiers
             */
            String modifier = null;
            int pos = flags.indexOf(':');
            if (pos > 0) {
                modifier = flags.substring(pos+1);
                flags = flags.substring(0, pos);
            }
D
duke 已提交
427 428 429
            /*
             * command modes
             */
W
weijun 已提交
430 431 432 433 434 435 436 437 438 439 440 441
            boolean isCommand = false;
            for (Command c: Command.values()) {
                if (collator.compare(flags, c.toString()) == 0) {
                    command = c;
                    isCommand = true;
                    break;
                }
            }

            if (isCommand) {
                // already recognized as a command
            } else if (collator.compare(flags, "-export") == 0) {
D
duke 已提交
442
                command = EXPORTCERT;
W
weijun 已提交
443
            } else if (collator.compare(flags, "-genkey") == 0) {
D
duke 已提交
444
                command = GENKEYPAIR;
W
weijun 已提交
445
            } else if (collator.compare(flags, "-import") == 0) {
D
duke 已提交
446
                command = IMPORTCERT;
447 448
            } else if (collator.compare(flags, "-importpassword") == 0) {
                command = IMPORTPASS;
449
            } else if (collator.compare(flags, "-help") == 0) {
W
weijun 已提交
450
                help = true;
451 452
            } else if (collator.compare(flags, "-nowarn") == 0) {
                nowarn = true;
D
duke 已提交
453 454 455 456 457 458 459
            }

            /*
             * specifiers
             */
            else if (collator.compare(flags, "-keystore") == 0 ||
                    collator.compare(flags, "-destkeystore") == 0) {
W
weijun 已提交
460
                ksfname = args[++i];
D
duke 已提交
461 462
            } else if (collator.compare(flags, "-storepass") == 0 ||
                    collator.compare(flags, "-deststorepass") == 0) {
463
                storePass = getPass(modifier, args[++i]);
D
duke 已提交
464 465 466
                passwords.add(storePass);
            } else if (collator.compare(flags, "-storetype") == 0 ||
                    collator.compare(flags, "-deststoretype") == 0) {
467
                storetype = KeyStoreUtil.niceStoreTypeName(args[++i]);
D
duke 已提交
468
            } else if (collator.compare(flags, "-srcstorepass") == 0) {
469
                srcstorePass = getPass(modifier, args[++i]);
D
duke 已提交
470 471
                passwords.add(srcstorePass);
            } else if (collator.compare(flags, "-srcstoretype") == 0) {
472
                srcstoretype = KeyStoreUtil.niceStoreTypeName(args[++i]);
D
duke 已提交
473
            } else if (collator.compare(flags, "-srckeypass") == 0) {
474
                srckeyPass = getPass(modifier, args[++i]);
D
duke 已提交
475 476
                passwords.add(srckeyPass);
            } else if (collator.compare(flags, "-srcprovidername") == 0) {
W
weijun 已提交
477
                srcProviderName = args[++i];
D
duke 已提交
478 479
            } else if (collator.compare(flags, "-providername") == 0 ||
                    collator.compare(flags, "-destprovidername") == 0) {
W
weijun 已提交
480
                providerName = args[++i];
D
duke 已提交
481
            } else if (collator.compare(flags, "-providerpath") == 0) {
W
weijun 已提交
482
                pathlist = args[++i];
D
duke 已提交
483
            } else if (collator.compare(flags, "-keypass") == 0) {
484
                keyPass = getPass(modifier, args[++i]);
D
duke 已提交
485 486
                passwords.add(keyPass);
            } else if (collator.compare(flags, "-new") == 0) {
487
                newPass = getPass(modifier, args[++i]);
D
duke 已提交
488 489
                passwords.add(newPass);
            } else if (collator.compare(flags, "-destkeypass") == 0) {
490
                destKeyPass = getPass(modifier, args[++i]);
D
duke 已提交
491 492 493
                passwords.add(destKeyPass);
            } else if (collator.compare(flags, "-alias") == 0 ||
                    collator.compare(flags, "-srcalias") == 0) {
W
weijun 已提交
494
                alias = args[++i];
D
duke 已提交
495 496
            } else if (collator.compare(flags, "-dest") == 0 ||
                    collator.compare(flags, "-destalias") == 0) {
W
weijun 已提交
497
                dest = args[++i];
D
duke 已提交
498
            } else if (collator.compare(flags, "-dname") == 0) {
W
weijun 已提交
499
                dname = args[++i];
D
duke 已提交
500
            } else if (collator.compare(flags, "-keysize") == 0) {
W
weijun 已提交
501
                keysize = Integer.parseInt(args[++i]);
D
duke 已提交
502
            } else if (collator.compare(flags, "-keyalg") == 0) {
W
weijun 已提交
503
                keyAlgName = args[++i];
D
duke 已提交
504
            } else if (collator.compare(flags, "-sigalg") == 0) {
W
weijun 已提交
505
                sigAlgName = args[++i];
D
duke 已提交
506
            } else if (collator.compare(flags, "-startdate") == 0) {
W
weijun 已提交
507
                startDate = args[++i];
D
duke 已提交
508
            } else if (collator.compare(flags, "-validity") == 0) {
W
weijun 已提交
509
                validity = Long.parseLong(args[++i]);
510
            } else if (collator.compare(flags, "-ext") == 0) {
W
weijun 已提交
511
                v3ext.add(args[++i]);
512 513
            } else if (collator.compare(flags, "-id") == 0) {
                ids.add(args[++i]);
D
duke 已提交
514
            } else if (collator.compare(flags, "-file") == 0) {
W
weijun 已提交
515
                filename = args[++i];
516
            } else if (collator.compare(flags, "-infile") == 0) {
W
weijun 已提交
517
                infilename = args[++i];
518
            } else if (collator.compare(flags, "-outfile") == 0) {
W
weijun 已提交
519
                outfilename = args[++i];
520
            } else if (collator.compare(flags, "-sslserver") == 0) {
W
weijun 已提交
521
                sslserver = args[++i];
522 523
            } else if (collator.compare(flags, "-jarfile") == 0) {
                jarfile = args[++i];
D
duke 已提交
524
            } else if (collator.compare(flags, "-srckeystore") == 0) {
W
weijun 已提交
525
                srcksfname = args[++i];
D
duke 已提交
526 527 528 529 530
            } else if ((collator.compare(flags, "-provider") == 0) ||
                        (collator.compare(flags, "-providerclass") == 0)) {
                if (providers == null) {
                    providers = new HashSet<Pair <String, String>> (3);
                }
W
weijun 已提交
531
                String providerClass = args[++i];
D
duke 已提交
532 533 534 535 536 537 538 539 540 541 542
                String providerArg = null;

                if (args.length > (i+1)) {
                    flags = args[i+1];
                    if (collator.compare(flags, "-providerarg") == 0) {
                        if (args.length == (i+2)) errorNeedArgument(flags);
                        providerArg = args[i+2];
                        i += 2;
                    }
                }
                providers.add(
543
                        Pair.of(providerClass, providerArg));
D
duke 已提交
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
            }

            /*
             * options
             */
            else if (collator.compare(flags, "-v") == 0) {
                verbose = true;
            } else if (collator.compare(flags, "-debug") == 0) {
                debug = true;
            } else if (collator.compare(flags, "-rfc") == 0) {
                rfc = true;
            } else if (collator.compare(flags, "-noprompt") == 0) {
                noprompt = true;
            } else if (collator.compare(flags, "-trustcacerts") == 0) {
                trustcacerts = true;
            } else if (collator.compare(flags, "-protected") == 0 ||
                    collator.compare(flags, "-destprotected") == 0) {
                protectedPath = true;
            } else if (collator.compare(flags, "-srcprotected") == 0) {
                srcprotectedPath = true;
            } else  {
565
                System.err.println(rb.getString("Illegal.option.") + flags);
D
duke 已提交
566 567 568 569 570
                tinyHelp();
            }
        }

        if (i<args.length) {
571
            System.err.println(rb.getString("Illegal.option.") + args[i]);
W
weijun 已提交
572
            tinyHelp();
D
duke 已提交
573 574
        }

W
weijun 已提交
575 576 577 578
        if (command == null) {
            if (help) {
                usage();
            } else {
579
                System.err.println(rb.getString("Usage.error.no.command.provided"));
W
weijun 已提交
580 581 582 583 584
                tinyHelp();
            }
        } else if (help) {
            usage();
            command = null;
D
duke 已提交
585 586 587
        }
    }

W
weijun 已提交
588
    boolean isKeyStoreRelated(Command cmd) {
589 590 591
        return cmd != PRINTCERT && cmd != PRINTCERTREQ;
    }

592

D
duke 已提交
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
    /**
     * Execute the commands.
     */
    void doCommands(PrintStream out) throws Exception {
        if (P11KEYSTORE.equalsIgnoreCase(storetype) ||
                KeyStoreUtil.isWindowsKeyStore(storetype)) {
            token = true;
            if (ksfname == null) {
                ksfname = NONE;
            }
        }
        if (NONE.equals(ksfname)) {
            nullStream = true;
        }

        if (token && !nullStream) {
            System.err.println(MessageFormat.format(rb.getString
610
                (".keystore.must.be.NONE.if.storetype.is.{0}"), storetype));
D
duke 已提交
611 612 613 614 615 616 617
            System.err.println();
            tinyHelp();
        }

        if (token &&
            (command == KEYPASSWD || command == STOREPASSWD)) {
            throw new UnsupportedOperationException(MessageFormat.format(rb.getString
618
                        (".storepasswd.and.keypasswd.commands.not.supported.if.storetype.is.{0}"), storetype));
D
duke 已提交
619 620 621 622
        }

        if (token && (keyPass != null || newPass != null || destKeyPass != null)) {
            throw new IllegalArgumentException(MessageFormat.format(rb.getString
623
                (".keypass.and.new.can.not.be.specified.if.storetype.is.{0}"), storetype));
D
duke 已提交
624 625 626 627 628 629
        }

        if (protectedPath) {
            if (storePass != null || keyPass != null ||
                    newPass != null || destKeyPass != null) {
                throw new IllegalArgumentException(rb.getString
630
                        ("if.protected.is.specified.then.storepass.keypass.and.new.must.not.be.specified"));
D
duke 已提交
631 632 633 634 635 636
            }
        }

        if (srcprotectedPath) {
            if (srcstorePass != null || srckeyPass != null) {
                throw new IllegalArgumentException(rb.getString
637
                        ("if.srcprotected.is.specified.then.srcstorepass.and.srckeypass.must.not.be.specified"));
D
duke 已提交
638 639 640 641 642 643 644
            }
        }

        if (KeyStoreUtil.isWindowsKeyStore(storetype)) {
            if (storePass != null || keyPass != null ||
                    newPass != null || destKeyPass != null) {
                throw new IllegalArgumentException(rb.getString
645
                        ("if.keystore.is.not.password.protected.then.storepass.keypass.and.new.must.not.be.specified"));
D
duke 已提交
646 647 648 649 650 651
            }
        }

        if (KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {
            if (srcstorePass != null || srckeyPass != null) {
                throw new IllegalArgumentException(rb.getString
652
                        ("if.source.keystore.is.not.password.protected.then.srcstorepass.and.srckeypass.must.not.be.specified"));
D
duke 已提交
653 654 655 656 657
            }
        }

        if (validity <= (long)0) {
            throw new Exception
658
                (rb.getString("Validity.must.be.greater.than.zero"));
D
duke 已提交
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
        }

        // Try to load and install specified provider
        if (providers != null) {
            ClassLoader cl = null;
            if (pathlist != null) {
                String path = null;
                path = PathList.appendPath(
                        path, System.getProperty("java.class.path"));
                path = PathList.appendPath(
                        path, System.getProperty("env.class.path"));
                path = PathList.appendPath(path, pathlist);

                URL[] urls = PathList.pathToURLs(path);
                cl = new URLClassLoader(urls);
            } else {
                cl = ClassLoader.getSystemClassLoader();
            }

            for (Pair <String, String> provider: providers) {
                String provName = provider.fst;
                Class<?> provClass;
                if (cl != null) {
                    provClass = cl.loadClass(provName);
                } else {
                    provClass = Class.forName(provName);
                }

                String provArg = provider.snd;
                Object obj;
                if (provArg == null) {
                    obj = provClass.newInstance();
                } else {
                    Constructor<?> c = provClass.getConstructor(PARAM_STRING);
                    obj = c.newInstance(provArg);
                }
                if (!(obj instanceof Provider)) {
                    MessageFormat form = new MessageFormat
697
                        (rb.getString("provName.not.a.provider"));
D
duke 已提交
698 699 700 701 702 703 704 705 706
                    Object[] source = {provName};
                    throw new Exception(form.format(source));
                }
                Security.addProvider((Provider)obj);
            }
        }

        if (command == LIST && verbose && rfc) {
            System.err.println(rb.getString
707
                ("Must.not.specify.both.v.and.rfc.with.list.command"));
D
duke 已提交
708 709 710 711 712 713
            tinyHelp();
        }

        // Make sure provided passwords are at least 6 characters long
        if (command == GENKEYPAIR && keyPass!=null && keyPass.length < 6) {
            throw new Exception(rb.getString
714
                ("Key.password.must.be.at.least.6.characters"));
D
duke 已提交
715 716 717
        }
        if (newPass != null && newPass.length < 6) {
            throw new Exception(rb.getString
718
                ("New.password.must.be.at.least.6.characters"));
D
duke 已提交
719 720 721
        }
        if (destKeyPass != null && destKeyPass.length < 6) {
            throw new Exception(rb.getString
722
                ("New.password.must.be.at.least.6.characters"));
D
duke 已提交
723 724
        }

725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
        // Set this before inplaceImport check so we can compare name.
        if (ksfname == null) {
            ksfname = System.getProperty("user.home") + File.separator
                    + ".keystore";
        }

        KeyStore srcKeyStore = null;
        if (command == IMPORTKEYSTORE) {
            inplaceImport = inplaceImportCheck();
            if (inplaceImport) {
                // We load srckeystore first so we have srcstorePass that
                // can be assigned to storePass
                srcKeyStore = loadSourceKeyStore();
                if (storePass == null) {
                    storePass = srcstorePass;
                }
            }
        }

D
duke 已提交
744 745 746 747 748 749
        // Check if keystore exists.
        // If no keystore has been specified at the command line, try to use
        // the default, which is located in $HOME/.keystore.
        // If the command is "genkey", "identitydb", "import", or "printcert",
        // it is OK not to have a keystore.

750 751 752
        // DO NOT open the existing keystore if this is an in-place import.
        // The keystore should be created as brand new.
        if (isKeyStoreRelated(command) && !nullStream && !inplaceImport) {
D
duke 已提交
753 754 755 756 757
                try {
                    ksfile = new File(ksfname);
                    // Check if keystore file is empty
                    if (ksfile.exists() && ksfile.length() == 0) {
                        throw new Exception(rb.getString
758
                        ("Keystore.file.exists.but.is.empty.") + ksfname);
D
duke 已提交
759 760 761 762 763 764 765
                    }
                    ksStream = new FileInputStream(ksfile);
                } catch (FileNotFoundException e) {
                    if (command != GENKEYPAIR &&
                        command != GENSECKEY &&
                        command != IDENTITYDB &&
                        command != IMPORTCERT &&
766
                        command != IMPORTPASS &&
767 768
                        command != IMPORTKEYSTORE &&
                        command != PRINTCRL) {
D
duke 已提交
769
                        throw new Exception(rb.getString
770
                                ("Keystore.file.does.not.exist.") + ksfname);
D
duke 已提交
771 772 773 774 775 776 777 778 779
                    }
                }
            }

        if ((command == KEYCLONE || command == CHANGEALIAS)
                && dest == null) {
            dest = getAlias("destination");
            if ("".equals(dest)) {
                throw new Exception(rb.getString
780
                        ("Must.specify.destination.alias"));
D
duke 已提交
781 782 783 784 785 786
            }
        }

        if (command == DELETE && alias == null) {
            alias = getAlias(null);
            if ("".equals(alias)) {
787
                throw new Exception(rb.getString("Must.specify.alias"));
D
duke 已提交
788 789 790 791
            }
        }

        // Create new keystore
792 793 794
        if (storetype == null) {
            storetype = KeyStore.getDefaultType();
        }
D
duke 已提交
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
        if (providerName == null) {
            keyStore = KeyStore.getInstance(storetype);
        } else {
            keyStore = KeyStore.getInstance(storetype, providerName);
        }

        /*
         * Load the keystore data.
         *
         * At this point, it's OK if no keystore password has been provided.
         * We want to make sure that we can load the keystore data, i.e.,
         * the keystore data has the right format. If we cannot load the
         * keystore, why bother asking the user for his or her password?
         * Only if we were able to load the keystore, and no keystore
         * password has been provided, will we prompt the user for the
         * keystore password to verify the keystore integrity.
         * This means that the keystore is loaded twice: first load operation
         * checks the keystore format, second load operation verifies the
         * keystore integrity.
         *
         * If the keystore password has already been provided (at the
         * command line), however, the keystore is loaded only once, and the
         * keystore format and integrity are checked "at the same time".
         *
         * Null stream keystores are loaded later.
         */
        if (!nullStream) {
822 823 824
            if (inplaceImport) {
                keyStore.load(null, storePass);
            } else {
D
duke 已提交
825
            keyStore.load(ksStream, storePass);
826
            }
D
duke 已提交
827 828 829 830 831
            if (ksStream != null) {
                ksStream.close();
            }
        }

832 833 834 835 836
        if (P12KEYSTORE.equalsIgnoreCase(storetype) && command == KEYPASSWD) {
            throw new UnsupportedOperationException(rb.getString
                    (".keypasswd.commands.not.supported.if.storetype.is.PKCS12"));
        }

D
duke 已提交
837 838 839 840 841 842 843 844 845 846
        // All commands that create or modify the keystore require a keystore
        // password.

        if (nullStream && storePass != null) {
            keyStore.load(null, storePass);
        } else if (!nullStream && storePass != null) {
            // If we are creating a new non nullStream-based keystore,
            // insist that the password be at least 6 characters
            if (ksStream == null && storePass.length < 6) {
                throw new Exception(rb.getString
847
                        ("Keystore.password.must.be.at.least.6.characters"));
D
duke 已提交
848 849 850 851 852 853 854 855 856 857 858
            }
        } else if (storePass == null) {

            // only prompt if (protectedPath == false)

            if (!protectedPath && !KeyStoreUtil.isWindowsKeyStore(storetype) &&
                (command == CERTREQ ||
                        command == DELETE ||
                        command == GENKEYPAIR ||
                        command == GENSECKEY ||
                        command == IMPORTCERT ||
859
                        command == IMPORTPASS ||
D
duke 已提交
860 861 862 863 864 865 866 867 868 869 870
                        command == IMPORTKEYSTORE ||
                        command == KEYCLONE ||
                        command == CHANGEALIAS ||
                        command == SELFCERT ||
                        command == STOREPASSWD ||
                        command == KEYPASSWD ||
                        command == IDENTITYDB)) {
                int count = 0;
                do {
                    if (command == IMPORTKEYSTORE) {
                        System.err.print
871
                                (rb.getString("Enter.destination.keystore.password."));
D
duke 已提交
872 873
                    } else {
                        System.err.print
874
                                (rb.getString("Enter.keystore.password."));
D
duke 已提交
875 876 877 878 879 880 881 882 883
                    }
                    System.err.flush();
                    storePass = Password.readPassword(System.in);
                    passwords.add(storePass);

                    // If we are creating a new non nullStream-based keystore,
                    // insist that the password be at least 6 characters
                    if (!nullStream && (storePass == null || storePass.length < 6)) {
                        System.err.println(rb.getString
884
                                ("Keystore.password.is.too.short.must.be.at.least.6.characters"));
D
duke 已提交
885 886 887 888 889 890
                        storePass = null;
                    }

                    // If the keystore file does not exist and needs to be
                    // created, the storepass should be prompted twice.
                    if (storePass != null && !nullStream && ksStream == null) {
891
                        System.err.print(rb.getString("Re.enter.new.password."));
D
duke 已提交
892 893 894 895
                        char[] storePassAgain = Password.readPassword(System.in);
                        passwords.add(storePassAgain);
                        if (!Arrays.equals(storePass, storePassAgain)) {
                            System.err.println
896
                                (rb.getString("They.don.t.match.Try.again"));
D
duke 已提交
897 898 899 900 901 902 903 904 905 906
                            storePass = null;
                        }
                    }

                    count++;
                } while ((storePass == null) && count < 3);


                if (storePass == null) {
                    System.err.println
907
                        (rb.getString("Too.many.failures.try.later"));
D
duke 已提交
908 909 910 911
                    return;
                }
            } else if (!protectedPath
                    && !KeyStoreUtil.isWindowsKeyStore(storetype)
912
                    && isKeyStoreRelated(command)) {
D
duke 已提交
913
                // here we have EXPORTCERT and LIST (info valid until STOREPASSWD)
914
                if (command != PRINTCRL) {
915
                    System.err.print(rb.getString("Enter.keystore.password."));
916 917 918 919
                    System.err.flush();
                    storePass = Password.readPassword(System.in);
                    passwords.add(storePass);
                }
D
duke 已提交
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
            }

            // Now load a nullStream-based keystore,
            // or verify the integrity of an input stream-based keystore
            if (nullStream) {
                keyStore.load(null, storePass);
            } else if (ksStream != null) {
                ksStream = new FileInputStream(ksfile);
                keyStore.load(ksStream, storePass);
                ksStream.close();
            }
        }

        if (storePass != null && P12KEYSTORE.equalsIgnoreCase(storetype)) {
            MessageFormat form = new MessageFormat(rb.getString(
935
                "Warning.Different.store.and.key.passwords.not.supported.for.PKCS12.KeyStores.Ignoring.user.specified.command.value."));
D
duke 已提交
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
            if (keyPass != null && !Arrays.equals(storePass, keyPass)) {
                Object[] source = {"-keypass"};
                System.err.println(form.format(source));
                keyPass = storePass;
            }
            if (newPass != null && !Arrays.equals(storePass, newPass)) {
                Object[] source = {"-new"};
                System.err.println(form.format(source));
                newPass = storePass;
            }
            if (destKeyPass != null && !Arrays.equals(storePass, destKeyPass)) {
                Object[] source = {"-destkeypass"};
                System.err.println(form.format(source));
                destKeyPass = storePass;
            }
        }

        // Create a certificate factory
        if (command == PRINTCERT || command == IMPORTCERT
955
                || command == IDENTITYDB || command == PRINTCRL) {
D
duke 已提交
956 957 958
            cf = CertificateFactory.getInstance("X509");
        }

959 960 961 962 963 964 965
        // -trustcacerts can only be specified on -importcert.
        // Reset it so that warnings on CA cert will remain for
        // -printcert, etc.
        if (command != IMPORTCERT) {
            trustcacerts = false;
        }

D
duke 已提交
966
        if (trustcacerts) {
967
            caks = KeyStoreUtil.getCacertsKeyStore();
D
duke 已提交
968 969 970 971 972
        }

        // Perform the specified command
        if (command == CERTREQ) {
            if (filename != null) {
973 974 975
                try (PrintStream ps = new PrintStream(new FileOutputStream
                                                      (filename))) {
                    doCertReq(alias, sigAlgName, ps);
D
duke 已提交
976
                }
977 978
            } else {
                doCertReq(alias, sigAlgName, out);
D
duke 已提交
979 980 981
            }
            if (verbose && filename != null) {
                MessageFormat form = new MessageFormat(rb.getString
982
                        ("Certification.request.stored.in.file.filename."));
D
duke 已提交
983 984
                Object[] source = {filename};
                System.err.println(form.format(source));
985
                System.err.println(rb.getString("Submit.this.to.your.CA"));
D
duke 已提交
986 987 988 989 990 991
            }
        } else if (command == DELETE) {
            doDeleteEntry(alias);
            kssave = true;
        } else if (command == EXPORTCERT) {
            if (filename != null) {
992 993 994
                try (PrintStream ps = new PrintStream(new FileOutputStream
                                                   (filename))) {
                    doExportCert(alias, ps);
D
duke 已提交
995
                }
996 997
            } else {
                doExportCert(alias, out);
D
duke 已提交
998 999 1000
            }
            if (filename != null) {
                MessageFormat form = new MessageFormat(rb.getString
1001
                        ("Certificate.stored.in.file.filename."));
D
duke 已提交
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
                Object[] source = {filename};
                System.err.println(form.format(source));
            }
        } else if (command == GENKEYPAIR) {
            if (keyAlgName == null) {
                keyAlgName = "DSA";
            }
            doGenKeyPair(alias, dname, keyAlgName, keysize, sigAlgName);
            kssave = true;
        } else if (command == GENSECKEY) {
            if (keyAlgName == null) {
                keyAlgName = "DES";
            }
            doGenSecretKey(alias, keyAlgName, keysize);
            kssave = true;
1017 1018 1019 1020 1021 1022 1023
        } else if (command == IMPORTPASS) {
            if (keyAlgName == null) {
                keyAlgName = "PBE";
            }
            // password is stored as a secret key
            doGenSecretKey(alias, keyAlgName, keysize);
            kssave = true;
D
duke 已提交
1024 1025
        } else if (command == IDENTITYDB) {
            if (filename != null) {
1026 1027
                try (InputStream inStream = new FileInputStream(filename)) {
                    doImportIdentityDatabase(inStream);
D
duke 已提交
1028
                }
1029 1030
            } else {
                doImportIdentityDatabase(System.in);
D
duke 已提交
1031 1032 1033 1034 1035 1036
            }
        } else if (command == IMPORTCERT) {
            InputStream inStream = System.in;
            if (filename != null) {
                inStream = new FileInputStream(filename);
            }
1037
            String importAlias = (alias!=null)?alias:keyAlias;
D
duke 已提交
1038
            try {
1039 1040 1041 1042 1043
                if (keyStore.entryInstanceOf(
                        importAlias, KeyStore.PrivateKeyEntry.class)) {
                    kssave = installReply(importAlias, inStream);
                    if (kssave) {
                        System.err.println(rb.getString
1044
                            ("Certificate.reply.was.installed.in.keystore"));
1045 1046
                    } else {
                        System.err.println(rb.getString
1047
                            ("Certificate.reply.was.not.installed.in.keystore"));
1048 1049 1050 1051 1052 1053 1054
                    }
                } else if (!keyStore.containsAlias(importAlias) ||
                        keyStore.entryInstanceOf(importAlias,
                            KeyStore.TrustedCertificateEntry.class)) {
                    kssave = addTrustedCert(importAlias, inStream);
                    if (kssave) {
                        System.err.println(rb.getString
1055
                            ("Certificate.was.added.to.keystore"));
1056 1057
                    } else {
                        System.err.println(rb.getString
1058
                            ("Certificate.was.not.added.to.keystore"));
1059
                    }
D
duke 已提交
1060 1061 1062 1063 1064 1065 1066
                }
            } finally {
                if (inStream != System.in) {
                    inStream.close();
                }
            }
        } else if (command == IMPORTKEYSTORE) {
1067 1068 1069 1070 1071
            // When not in-place import, srcKeyStore is not loaded yet.
            if (srcKeyStore == null) {
                srcKeyStore = loadSourceKeyStore();
            }
            doImportKeyStore(srcKeyStore);
D
duke 已提交
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
            kssave = true;
        } else if (command == KEYCLONE) {
            keyPassNew = newPass;

            // added to make sure only key can go thru
            if (alias == null) {
                alias = keyAlias;
            }
            if (keyStore.containsAlias(alias) == false) {
                MessageFormat form = new MessageFormat
1082
                    (rb.getString("Alias.alias.does.not.exist"));
D
duke 已提交
1083 1084 1085 1086 1087
                Object[] source = {alias};
                throw new Exception(form.format(source));
            }
            if (!keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
                MessageFormat form = new MessageFormat(rb.getString(
1088
                        "Alias.alias.references.an.entry.type.that.is.not.a.private.key.entry.The.keyclone.command.only.supports.cloning.of.private.key"));
D
duke 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
                Object[] source = {alias};
                throw new Exception(form.format(source));
            }

            doCloneEntry(alias, dest, true);  // Now everything can be cloned
            kssave = true;
        } else if (command == CHANGEALIAS) {
            if (alias == null) {
                alias = keyAlias;
            }
            doCloneEntry(alias, dest, false);
            // in PKCS11, clone a PrivateKeyEntry will delete the old one
            if (keyStore.containsAlias(alias)) {
                doDeleteEntry(alias);
            }
            kssave = true;
        } else if (command == KEYPASSWD) {
            keyPassNew = newPass;
            doChangeKeyPasswd(alias);
            kssave = true;
        } else if (command == LIST) {
1110 1111
            if (storePass == null
                    && !KeyStoreUtil.isWindowsKeyStore(storetype)) {
1112
                printNoIntegrityWarning();
1113 1114
            }

D
duke 已提交
1115
            if (alias != null) {
1116
                doPrintEntry(rb.getString("the.certificate"), alias, out);
D
duke 已提交
1117 1118 1119 1120
            } else {
                doPrintEntries(out);
            }
        } else if (command == PRINTCERT) {
1121
            doPrintCert(out);
D
duke 已提交
1122 1123 1124 1125 1126 1127 1128 1129 1130
        } else if (command == SELFCERT) {
            doSelfCert(alias, dname, sigAlgName);
            kssave = true;
        } else if (command == STOREPASSWD) {
            storePassNew = newPass;
            if (storePassNew == null) {
                storePassNew = getNewPasswd("keystore password", storePass);
            }
            kssave = true;
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
        } else if (command == GENCERT) {
            if (alias == null) {
                alias = keyAlias;
            }
            InputStream inStream = System.in;
            if (infilename != null) {
                inStream = new FileInputStream(infilename);
            }
            PrintStream ps = null;
            if (outfilename != null) {
                ps = new PrintStream(new FileOutputStream(outfilename));
                out = ps;
            }
            try {
                doGenCert(alias, sigAlgName, inStream, out);
            } finally {
                if (inStream != System.in) {
                    inStream.close();
                }
                if (ps != null) {
                    ps.close();
                }
            }
1154 1155 1156 1157 1158
        } else if (command == GENCRL) {
            if (alias == null) {
                alias = keyAlias;
            }
            if (filename != null) {
1159 1160 1161
                try (PrintStream ps =
                         new PrintStream(new FileOutputStream(filename))) {
                    doGenCRL(ps);
1162
                }
1163 1164
            } else {
                doGenCRL(out);
1165
            }
1166 1167
        } else if (command == PRINTCERTREQ) {
            if (filename != null) {
1168 1169
                try (InputStream inStream = new FileInputStream(filename)) {
                    doPrintCertReq(inStream, out);
1170
                }
1171 1172
            } else {
                doPrintCertReq(System.in, out);
1173
            }
1174 1175
        } else if (command == PRINTCRL) {
            doPrintCRL(filename, out);
D
duke 已提交
1176 1177 1178 1179 1180 1181
        }

        // If we need to save the keystore, do so.
        if (kssave) {
            if (verbose) {
                MessageFormat form = new MessageFormat
1182
                        (rb.getString(".Storing.ksfname."));
D
duke 已提交
1183 1184 1185 1186 1187 1188 1189
                Object[] source = {nullStream ? "keystore" : ksfname};
                System.err.println(form.format(source));
            }

            if (token) {
                keyStore.store(null, null);
            } else {
W
weijun 已提交
1190 1191 1192 1193 1194 1195 1196 1197
                char[] pass = (storePassNew!=null) ? storePassNew : storePass;
                if (nullStream) {
                    keyStore.store(null, pass);
                } else {
                    ByteArrayOutputStream bout = new ByteArrayOutputStream();
                    keyStore.store(bout, pass);
                    try (FileOutputStream fout = new FileOutputStream(ksfname)) {
                        fout.write(bout.toByteArray());
D
duke 已提交
1198 1199 1200 1201
                    }
                }
            }
        }
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260

        if (isKeyStoreRelated(command)
                && !token && !nullStream && ksfname != null) {

            // JKS storetype warning on the final result keystore
            File f = new File(ksfname);
            if (f.exists()) {
                // Read the first 4 bytes to determine
                // if we're dealing with JKS/JCEKS type store
                String realType = keyStoreType(f);
                if (realType.equalsIgnoreCase("JKS")
                    || realType.equalsIgnoreCase("JCEKS")) {
                    boolean allCerts = true;
                    for (String a : Collections.list(keyStore.aliases())) {
                        if (!keyStore.entryInstanceOf(
                                a, TrustedCertificateEntry.class)) {
                            allCerts = false;
                            break;
                        }
                    }
                    // Don't warn for "cacerts" style keystore.
                    if (!allCerts) {
                        weakWarnings.add(String.format(
                                rb.getString("jks.storetype.warning"),
                                realType, ksfname));
                    }
                }
                if (inplaceImport) {
                    String realSourceStoreType =
                        keyStoreType(new File(inplaceBackupName));
                    String format =
                            realType.equalsIgnoreCase(realSourceStoreType) ?
                            rb.getString("backup.keystore.warning") :
                            rb.getString("migrate.keystore.warning");
                    weakWarnings.add(
                            String.format(format,
                                    srcksfname,
                                    realSourceStoreType,
                                    inplaceBackupName,
                                    realType));
                }
            }
        }
    }

    private String keyStoreType(File f) throws IOException {
        int MAGIC = 0xfeedfeed;
        int JCEKS_MAGIC = 0xcececece;
        try (DataInputStream dis = new DataInputStream(
            new FileInputStream(f))) {
            int xMagic = dis.readInt();
            if (xMagic == MAGIC) {
                return "JKS";
            } else if (xMagic == JCEKS_MAGIC) {
                return "JCEKS";
            } else {
                return "Non JKS/JCEKS";
            }
        }
D
duke 已提交
1261 1262
    }

1263 1264 1265 1266 1267 1268 1269 1270 1271
    /**
     * Generate a certificate: Read PKCS10 request from in, and print
     * certificate to out. Use alias as CA, sigAlgName as the signature
     * type.
     */
    private void doGenCert(String alias, String sigAlgName, InputStream in, PrintStream out)
            throws Exception {


1272 1273 1274 1275 1276 1277
        if (keyStore.containsAlias(alias) == false) {
            MessageFormat form = new MessageFormat
                    (rb.getString("Alias.alias.does.not.exist"));
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }
1278 1279 1280 1281 1282
        Certificate signerCert = keyStore.getCertificate(alias);
        byte[] encoded = signerCert.getEncoded();
        X509CertImpl signerCertImpl = new X509CertImpl(encoded);
        X509CertInfo signerCertInfo = (X509CertInfo)signerCertImpl.get(
                X509CertImpl.NAME + "." + X509CertImpl.INFO);
1283
        X500Name issuer = (X500Name)signerCertInfo.get(X509CertInfo.SUBJECT + "." +
1284
                                           X509CertInfo.DN_NAME);
1285 1286 1287 1288 1289 1290 1291

        Date firstDate = getStartDate(startDate);
        Date lastDate = new Date();
        lastDate.setTime(firstDate.getTime() + validity*1000L*24L*60L*60L);
        CertificateValidity interval = new CertificateValidity(firstDate,
                                                               lastDate);

1292 1293
        PrivateKey privateKey =
                (PrivateKey)recoverKey(alias, storePass, keyPass).fst;
1294 1295 1296 1297
        if (sigAlgName == null) {
            sigAlgName = getCompatibleSigAlgName(privateKey.getAlgorithm());
        }
        Signature signature = Signature.getInstance(sigAlgName);
1298 1299 1300 1301
        AlgorithmParameterSpec params = AlgorithmId
                .getDefaultAlgorithmParameterSpec(sigAlgName, privateKey);

        SignatureUtil.initSignWithParam(signature, privateKey, params, null);
1302 1303

        X509CertInfo info = new X509CertInfo();
1304
        AlgorithmId algID = AlgorithmId.getWithParameterSpec(sigAlgName, params);
1305
        info.set(X509CertInfo.VALIDITY, interval);
1306 1307
        info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
                    new java.util.Random().nextInt() & 0x7fffffff));
1308
        info.set(X509CertInfo.VERSION,
1309
                    new CertificateVersion(CertificateVersion.V3));
1310
        info.set(X509CertInfo.ALGORITHM_ID,
1311
                    new CertificateAlgorithmId(algID));
1312
        info.set(X509CertInfo.ISSUER, issuer);
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        boolean canRead = false;
        StringBuffer sb = new StringBuffer();
        while (true) {
            String s = reader.readLine();
            if (s == null) break;
            // OpenSSL does not use NEW
            //if (s.startsWith("-----BEGIN NEW CERTIFICATE REQUEST-----")) {
            if (s.startsWith("-----BEGIN") && s.indexOf("REQUEST") >= 0) {
                canRead = true;
            //} else if (s.startsWith("-----END NEW CERTIFICATE REQUEST-----")) {
            } else if (s.startsWith("-----END") && s.indexOf("REQUEST") >= 0) {
                break;
            } else if (canRead) {
                sb.append(s);
            }
        }
1331
        byte[] rawReq = Pem.decode(new String(sb));
1332 1333
        PKCS10 req = new PKCS10(rawReq);

1334 1335
        checkWeak(rb.getString("the.certificate.request"), req);

1336
        info.set(X509CertInfo.KEY, new CertificateX509Key(req.getSubjectPublicKeyInfo()));
1337 1338
        info.set(X509CertInfo.SUBJECT,
                    dname==null?req.getSubjectName():new X500Name(dname));
1339 1340 1341 1342
        CertificateExtensions reqex = null;
        Iterator<PKCS10Attribute> attrs = req.getAttributes().getAttributes().iterator();
        while (attrs.hasNext()) {
            PKCS10Attribute attr = attrs.next();
1343
            if (attr.getAttributeId().equals((Object)PKCS9Attribute.EXTENSION_REQUEST_OID)) {
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
                reqex = (CertificateExtensions)attr.getAttributeValue();
            }
        }
        CertificateExtensions ext = createV3Extensions(
                reqex,
                null,
                v3ext,
                req.getSubjectPublicKeyInfo(),
                signerCert.getPublicKey());
        info.set(X509CertInfo.EXTENSIONS, ext);
        X509CertImpl cert = new X509CertImpl(info);
1355
        cert.sign(privateKey, params, sigAlgName, null);
1356
        dumpCert(cert, out);
1357 1358 1359
        for (Certificate ca: keyStore.getCertificateChain(alias)) {
            if (ca instanceof X509Certificate) {
                X509Certificate xca = (X509Certificate)ca;
1360
                if (!KeyStoreUtil.isSelfSigned(xca)) {
1361 1362 1363 1364
                    dumpCert(xca, out);
                }
            }
        }
1365 1366 1367

        checkWeak(rb.getString("the.issuer"), keyStore.getCertificateChain(alias));
        checkWeak(rb.getString("the.generated.certificate"), cert);
1368 1369
    }

1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
    private void doGenCRL(PrintStream out)
            throws Exception {
        if (ids == null) {
            throw new Exception("Must provide -id when -gencrl");
        }
        Certificate signerCert = keyStore.getCertificate(alias);
        byte[] encoded = signerCert.getEncoded();
        X509CertImpl signerCertImpl = new X509CertImpl(encoded);
        X509CertInfo signerCertInfo = (X509CertInfo)signerCertImpl.get(
                X509CertImpl.NAME + "." + X509CertImpl.INFO);
        X500Name owner = (X500Name)signerCertInfo.get(X509CertInfo.SUBJECT + "." +
1381
                                                      X509CertInfo.DN_NAME);
1382 1383 1384

        Date firstDate = getStartDate(startDate);
        Date lastDate = (Date) firstDate.clone();
1385
        lastDate.setTime(lastDate.getTime() + validity*1000*24*60*60);
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
        CertificateValidity interval = new CertificateValidity(firstDate,
                                                               lastDate);


        PrivateKey privateKey =
                (PrivateKey)recoverKey(alias, storePass, keyPass).fst;
        if (sigAlgName == null) {
            sigAlgName = getCompatibleSigAlgName(privateKey.getAlgorithm());
        }

        X509CRLEntry[] badCerts = new X509CRLEntry[ids.size()];
        for (int i=0; i<ids.size(); i++) {
            String id = ids.get(i);
            int d = id.indexOf(':');
            if (d >= 0) {
                CRLExtensions ext = new CRLExtensions();
                ext.set("Reason", new CRLReasonCodeExtension(Integer.parseInt(id.substring(d+1))));
                badCerts[i] = new X509CRLEntryImpl(new BigInteger(id.substring(0, d)),
                        firstDate, ext);
            } else {
                badCerts[i] = new X509CRLEntryImpl(new BigInteger(ids.get(i)), firstDate);
            }
        }
        X509CRLImpl crl = new X509CRLImpl(owner, firstDate, lastDate, badCerts);
        crl.sign(privateKey, sigAlgName);
        if (rfc) {
            out.println("-----BEGIN X509 CRL-----");
1413
            out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(crl.getEncodedInternal()));
1414 1415 1416 1417
            out.println("-----END X509 CRL-----");
        } else {
            out.write(crl.getEncodedInternal());
        }
1418
        checkWeak(rb.getString("the.generated.crl"), crl, privateKey);
1419 1420
    }

D
duke 已提交
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
    /**
     * Creates a PKCS#10 cert signing request, corresponding to the
     * keys (and name) associated with a given alias.
     */
    private void doCertReq(String alias, String sigAlgName, PrintStream out)
        throws Exception
    {
        if (alias == null) {
            alias = keyAlias;
        }

1432 1433
        Pair<Key,char[]> objs = recoverKey(alias, storePass, keyPass);
        PrivateKey privKey = (PrivateKey)objs.fst;
D
duke 已提交
1434
        if (keyPass == null) {
1435
            keyPass = objs.snd;
D
duke 已提交
1436 1437 1438 1439 1440
        }

        Certificate cert = keyStore.getCertificate(alias);
        if (cert == null) {
            MessageFormat form = new MessageFormat
1441
                (rb.getString("alias.has.no.public.key.certificate."));
D
duke 已提交
1442 1443 1444 1445
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }
        PKCS10 request = new PKCS10(cert.getPublicKey());
1446 1447 1448 1449
        CertificateExtensions ext = createV3Extensions(null, null, v3ext, cert.getPublicKey(), null);
        // Attribute name is not significant
        request.getAttributes().setAttribute(X509CertInfo.EXTENSIONS,
                new PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID, ext));
D
duke 已提交
1450

1451
        // Construct a Signature object, so that we can sign the request
D
duke 已提交
1452
        if (sigAlgName == null) {
1453
            sigAlgName = getCompatibleSigAlgName(privKey.getAlgorithm());
D
duke 已提交
1454 1455 1456
        }

        Signature signature = Signature.getInstance(sigAlgName);
1457 1458 1459 1460
        AlgorithmParameterSpec params = AlgorithmId
                .getDefaultAlgorithmParameterSpec(sigAlgName, privKey);
        SignatureUtil.initSignWithParam(signature, privKey, params, null);

1461 1462 1463
        X500Name subject = dname == null?
                new X500Name(((X509Certificate)cert).getSubjectDN().toString()):
                new X500Name(dname);
D
duke 已提交
1464 1465

        // Sign the request and base-64 encode it
1466
        request.encodeAndSign(subject, signature);
D
duke 已提交
1467
        request.print(out);
1468 1469

        checkWeak(rb.getString("the.generated.certificate.request"), request);
D
duke 已提交
1470 1471 1472 1473 1474 1475 1476 1477
    }

    /**
     * Deletes an entry from the keystore.
     */
    private void doDeleteEntry(String alias) throws Exception {
        if (keyStore.containsAlias(alias) == false) {
            MessageFormat form = new MessageFormat
1478
                (rb.getString("Alias.alias.does.not.exist"));
D
duke 已提交
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }
        keyStore.deleteEntry(alias);
    }

    /**
     * Exports a certificate from the keystore.
     */
    private void doExportCert(String alias, PrintStream out)
        throws Exception
    {
        if (storePass == null
                && !KeyStoreUtil.isWindowsKeyStore(storetype)) {
1493
            printNoIntegrityWarning();
D
duke 已提交
1494 1495 1496 1497 1498 1499
        }
        if (alias == null) {
            alias = keyAlias;
        }
        if (keyStore.containsAlias(alias) == false) {
            MessageFormat form = new MessageFormat
1500
                (rb.getString("Alias.alias.does.not.exist"));
D
duke 已提交
1501 1502 1503 1504 1505 1506 1507
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }

        X509Certificate cert = (X509Certificate)keyStore.getCertificate(alias);
        if (cert == null) {
            MessageFormat form = new MessageFormat
1508
                (rb.getString("Alias.alias.has.no.certificate"));
D
duke 已提交
1509 1510 1511 1512
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }
        dumpCert(cert, out);
1513
        checkWeak(rb.getString("the.certificate"), cert);
D
duke 已提交
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
    }

    /**
     * Prompt the user for a keypass when generating a key entry.
     * @param alias the entry we will set password for
     * @param orig the original entry of doing a dup, null if generate new
     * @param origPass the password to copy from if user press ENTER
     */
    private char[] promptForKeyPass(String alias, String orig, char[] origPass) throws Exception{
        if (P12KEYSTORE.equalsIgnoreCase(storetype)) {
            return origPass;
W
weijun 已提交
1525
        } else if (!token && !protectedPath) {
D
duke 已提交
1526 1527 1528 1529
            // Prompt for key password
            int count;
            for (count = 0; count < 3; count++) {
                MessageFormat form = new MessageFormat(rb.getString
1530
                        ("Enter.key.password.for.alias."));
D
duke 已提交
1531 1532 1533 1534
                Object[] source = {alias};
                System.err.println(form.format(source));
                if (orig == null) {
                    System.err.print(rb.getString
1535
                            (".RETURN.if.same.as.keystore.password."));
D
duke 已提交
1536 1537
                } else {
                    form = new MessageFormat(rb.getString
1538
                            (".RETURN.if.same.as.for.otherAlias."));
D
duke 已提交
1539 1540 1541 1542 1543 1544 1545 1546 1547
                    Object[] src = {orig};
                    System.err.print(form.format(src));
                }
                System.err.flush();
                char[] entered = Password.readPassword(System.in);
                passwords.add(entered);
                if (entered == null) {
                    return origPass;
                } else if (entered.length >= 6) {
1548
                    System.err.print(rb.getString("Re.enter.new.password."));
D
duke 已提交
1549 1550 1551 1552
                    char[] passAgain = Password.readPassword(System.in);
                    passwords.add(passAgain);
                    if (!Arrays.equals(entered, passAgain)) {
                        System.err.println
1553
                            (rb.getString("They.don.t.match.Try.again"));
D
duke 已提交
1554 1555 1556 1557 1558
                        continue;
                    }
                    return entered;
                } else {
                    System.err.println(rb.getString
1559
                        ("Key.password.is.too.short.must.be.at.least.6.characters"));
D
duke 已提交
1560 1561 1562 1563 1564
                }
            }
            if (count == 3) {
                if (command == KEYCLONE) {
                    throw new Exception(rb.getString
1565
                        ("Too.many.failures.Key.entry.not.cloned"));
D
duke 已提交
1566 1567
                } else {
                    throw new Exception(rb.getString
1568
                            ("Too.many.failures.key.not.added.to.keystore"));
D
duke 已提交
1569 1570 1571
                }
            }
        }
W
weijun 已提交
1572
        return null;    // PKCS11, MSCAPI, or -protected
D
duke 已提交
1573
    }
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610

    /*
     * Prompt the user for the password credential to be stored.
     */
    private char[] promptForCredential() throws Exception {
        // Handle password supplied via stdin
        if (System.console() == null) {
            char[] importPass = Password.readPassword(System.in);
            passwords.add(importPass);
            return importPass;
        }

        int count;
        for (count = 0; count < 3; count++) {
            System.err.print(
                rb.getString("Enter.the.password.to.be.stored."));
            System.err.flush();
            char[] entered = Password.readPassword(System.in);
            passwords.add(entered);
            System.err.print(rb.getString("Re.enter.password."));
            char[] passAgain = Password.readPassword(System.in);
            passwords.add(passAgain);
            if (!Arrays.equals(entered, passAgain)) {
                System.err.println(rb.getString("They.don.t.match.Try.again"));
                continue;
            }
            return entered;
        }

        if (count == 3) {
            throw new Exception(rb.getString
                ("Too.many.failures.key.not.added.to.keystore"));
        }

        return null;
    }

D
duke 已提交
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
    /**
     * Creates a new secret key.
     */
    private void doGenSecretKey(String alias, String keyAlgName,
                              int keysize)
        throws Exception
    {
        if (alias == null) {
            alias = keyAlias;
        }
        if (keyStore.containsAlias(alias)) {
            MessageFormat form = new MessageFormat(rb.getString
1623
                ("Secret.key.not.generated.alias.alias.already.exists"));
D
duke 已提交
1624 1625 1626 1627
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }

1628 1629
        // Use the keystore's default PBE algorithm for entry protection
        boolean useDefaultPBEAlgorithm = true;
D
duke 已提交
1630
        SecretKey secKey = null;
1631

1632
        if (keyAlgName.toUpperCase(Locale.ENGLISH).startsWith("PBE")) {
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBE");

            // User is prompted for PBE credential
            secKey =
                factory.generateSecret(new PBEKeySpec(promptForCredential()));

            // Check whether a specific PBE algorithm was specified
            if (!"PBE".equalsIgnoreCase(keyAlgName)) {
                useDefaultPBEAlgorithm = false;
            }

            if (verbose) {
                MessageFormat form = new MessageFormat(rb.getString(
                    "Generated.keyAlgName.secret.key"));
                Object[] source =
                    {useDefaultPBEAlgorithm ? "PBE" : secKey.getAlgorithm()};
                System.err.println(form.format(source));
            }
D
duke 已提交
1651
        } else {
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
            KeyGenerator keygen = KeyGenerator.getInstance(keyAlgName);
            if (keysize == -1) {
                if ("DES".equalsIgnoreCase(keyAlgName)) {
                    keysize = 56;
                } else if ("DESede".equalsIgnoreCase(keyAlgName)) {
                    keysize = 168;
                } else {
                    throw new Exception(rb.getString
                        ("Please.provide.keysize.for.secret.key.generation"));
                }
            }
            keygen.init(keysize);
            secKey = keygen.generateKey();

            if (verbose) {
                MessageFormat form = new MessageFormat(rb.getString
                    ("Generated.keysize.bit.keyAlgName.secret.key"));
                Object[] source = {new Integer(keysize),
                                    secKey.getAlgorithm()};
                System.err.println(form.format(source));
            }
D
duke 已提交
1673 1674 1675 1676 1677
        }

        if (keyPass == null) {
            keyPass = promptForKeyPass(alias, null, storePass);
        }
1678 1679 1680 1681 1682 1683 1684

        if (useDefaultPBEAlgorithm) {
            keyStore.setKeyEntry(alias, secKey, keyPass, null);
        } else {
            keyStore.setEntry(alias, new KeyStore.SecretKeyEntry(secKey),
                new KeyStore.PasswordProtection(keyPass, keyAlgName, null));
        }
D
duke 已提交
1685 1686
    }

1687 1688 1689 1690 1691 1692 1693
    /**
     * If no signature algorithm was specified at the command line,
     * we choose one that is compatible with the selected private key
     */
    private static String getCompatibleSigAlgName(String keyAlgName)
            throws Exception {
        if ("DSA".equalsIgnoreCase(keyAlgName)) {
1694
            return "SHA256WithDSA";
1695
        } else if ("RSA".equalsIgnoreCase(keyAlgName)) {
1696
            return "SHA256WithRSA";
1697
        } else if ("EC".equalsIgnoreCase(keyAlgName)) {
1698
            return "SHA256withECDSA";
1699 1700
        } else {
            throw new Exception(rb.getString
1701
                    ("Cannot.derive.signature.algorithm"));
1702 1703
        }
    }
D
duke 已提交
1704 1705 1706 1707 1708 1709 1710 1711 1712
    /**
     * Creates a new key pair and self-signed certificate.
     */
    private void doGenKeyPair(String alias, String dname, String keyAlgName,
                              int keysize, String sigAlgName)
        throws Exception
    {
        if (keysize == -1) {
            if ("EC".equalsIgnoreCase(keyAlgName)) {
1713
                keysize = SecurityProviderConstants.DEF_EC_KEY_SIZE;
1714
            } else if ("RSA".equalsIgnoreCase(keyAlgName)) {
I
igerasim 已提交
1715
                keysize = SecurityProviderConstants.DEF_RSA_KEY_SIZE;
1716 1717
            } else if ("RSASSA-PSS".equalsIgnoreCase(keyAlgName)) {
                keysize = SecurityProviderConstants.DEF_RSASSA_PSS_KEY_SIZE;
1718
            } else if ("DSA".equalsIgnoreCase(keyAlgName)) {
I
igerasim 已提交
1719
                keysize = SecurityProviderConstants.DEF_DSA_KEY_SIZE;
D
duke 已提交
1720 1721 1722 1723 1724 1725 1726 1727 1728
            }
        }

        if (alias == null) {
            alias = keyAlias;
        }

        if (keyStore.containsAlias(alias)) {
            MessageFormat form = new MessageFormat(rb.getString
1729
                ("Key.pair.not.generated.alias.alias.already.exists"));
D
duke 已提交
1730 1731 1732 1733 1734
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }

        if (sigAlgName == null) {
1735
            sigAlgName = getCompatibleSigAlgName(keyAlgName);
D
duke 已提交
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
        }
        CertAndKeyGen keypair =
                new CertAndKeyGen(keyAlgName, sigAlgName, providerName);


        // If DN is provided, parse it. Otherwise, prompt the user for it.
        X500Name x500Name;
        if (dname == null) {
            x500Name = getX500Name();
        } else {
            x500Name = new X500Name(dname);
        }

        keypair.generate(keysize);
        PrivateKey privKey = keypair.getPrivateKey();

1752 1753 1754 1755 1756 1757 1758
        CertificateExtensions ext = createV3Extensions(
                null,
                null,
                v3ext,
                keypair.getPublicKeyAnyway(),
                null);

D
duke 已提交
1759 1760
        X509Certificate[] chain = new X509Certificate[1];
        chain[0] = keypair.getSelfCertificate(
1761
                x500Name, getStartDate(startDate), validity*24L*60L*60L, ext);
D
duke 已提交
1762 1763 1764

        if (verbose) {
            MessageFormat form = new MessageFormat(rb.getString
1765
                ("Generating.keysize.bit.keyAlgName.key.pair.and.self.signed.certificate.sigAlgName.with.a.validity.of.validality.days.for"));
D
duke 已提交
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
            Object[] source = {new Integer(keysize),
                                privKey.getAlgorithm(),
                                chain[0].getSigAlgName(),
                                new Long(validity),
                                x500Name};
            System.err.println(form.format(source));
        }

        if (keyPass == null) {
            keyPass = promptForKeyPass(alias, null, storePass);
        }
1777
        checkWeak(rb.getString("the.generated.certificate"), chain[0]);
1778
        keyStore.setKeyEntry(alias, privKey, keyPass, chain);
D
duke 已提交
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
    }

    /**
     * Clones an entry
     * @param orig original alias
     * @param dest destination alias
     * @changePassword if the password can be changed
     */
    private void doCloneEntry(String orig, String dest, boolean changePassword)
        throws Exception
    {
        if (orig == null) {
            orig = keyAlias;
        }

        if (keyStore.containsAlias(dest)) {
            MessageFormat form = new MessageFormat
1796
                (rb.getString("Destination.alias.dest.already.exists"));
D
duke 已提交
1797 1798 1799 1800
            Object[] source = {dest};
            throw new Exception(form.format(source));
        }

1801 1802 1803
        Pair<Entry,char[]> objs = recoverEntry(keyStore, orig, storePass, keyPass);
        Entry entry = objs.fst;
        keyPass = objs.snd;
D
duke 已提交
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828

        PasswordProtection pp = null;

        if (keyPass != null) {  // protected
            if (!changePassword || P12KEYSTORE.equalsIgnoreCase(storetype)) {
                keyPassNew = keyPass;
            } else {
                if (keyPassNew == null) {
                    keyPassNew = promptForKeyPass(dest, orig, keyPass);
                }
            }
            pp = new PasswordProtection(keyPassNew);
        }
        keyStore.setEntry(dest, entry, pp);
    }

    /**
     * Changes a key password.
     */
    private void doChangeKeyPasswd(String alias) throws Exception
    {

        if (alias == null) {
            alias = keyAlias;
        }
1829 1830
        Pair<Key,char[]> objs = recoverKey(alias, storePass, keyPass);
        Key privKey = objs.fst;
D
duke 已提交
1831
        if (keyPass == null) {
1832
            keyPass = objs.snd;
D
duke 已提交
1833 1834 1835 1836
        }

        if (keyPassNew == null) {
            MessageFormat form = new MessageFormat
1837
                (rb.getString("key.password.for.alias."));
D
duke 已提交
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
            Object[] source = {alias};
            keyPassNew = getNewPasswd(form.format(source), keyPass);
        }
        keyStore.setKeyEntry(alias, privKey, keyPassNew,
                             keyStore.getCertificateChain(alias));
    }

    /**
     * Imports a JDK 1.1-style identity database. We can only store one
     * certificate per identity, because we use the identity's name as the
     * alias (which references a keystore entry), and aliases must be unique.
     */
    private void doImportIdentityDatabase(InputStream in)
        throws Exception
    {
1853
        System.err.println(rb.getString
1854
            ("No.entries.from.identity.database.added"));
D
duke 已提交
1855 1856 1857 1858 1859
    }

    /**
     * Prints a single keystore entry.
     */
1860
    private void doPrintEntry(String label, String alias, PrintStream out)
D
duke 已提交
1861 1862 1863 1864
        throws Exception
    {
        if (keyStore.containsAlias(alias) == false) {
            MessageFormat form = new MessageFormat
1865
                (rb.getString("Alias.alias.does.not.exist"));
D
duke 已提交
1866 1867 1868 1869 1870 1871
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }

        if (verbose || rfc || debug) {
            MessageFormat form = new MessageFormat
1872
                (rb.getString("Alias.name.alias"));
D
duke 已提交
1873 1874 1875 1876 1877
            Object[] source = {alias};
            out.println(form.format(source));

            if (!token) {
                form = new MessageFormat(rb.getString
1878
                    ("Creation.date.keyStore.getCreationDate.alias."));
D
duke 已提交
1879 1880 1881 1882 1883 1884
                Object[] src = {keyStore.getCreationDate(alias)};
                out.println(form.format(src));
            }
        } else {
            if (!token) {
                MessageFormat form = new MessageFormat
1885
                    (rb.getString("alias.keyStore.getCreationDate.alias."));
D
duke 已提交
1886 1887 1888 1889
                Object[] source = {alias, keyStore.getCreationDate(alias)};
                out.print(form.format(source));
            } else {
                MessageFormat form = new MessageFormat
1890
                    (rb.getString("alias."));
D
duke 已提交
1891 1892 1893 1894 1895 1896 1897 1898 1899
                Object[] source = {alias};
                out.print(form.format(source));
            }
        }

        if (keyStore.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)) {
            if (verbose || rfc || debug) {
                Object[] source = {"SecretKeyEntry"};
                out.println(new MessageFormat(
1900
                        rb.getString("Entry.type.type.")).format(source));
D
duke 已提交
1901 1902 1903 1904 1905 1906 1907
            } else {
                out.println("SecretKeyEntry, ");
            }
        } else if (keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
            if (verbose || rfc || debug) {
                Object[] source = {"PrivateKeyEntry"};
                out.println(new MessageFormat(
1908
                        rb.getString("Entry.type.type.")).format(source));
D
duke 已提交
1909 1910 1911 1912 1913 1914 1915 1916 1917
            } else {
                out.println("PrivateKeyEntry, ");
            }

            // Get the chain
            Certificate[] chain = keyStore.getCertificateChain(alias);
            if (chain != null) {
                if (verbose || rfc || debug) {
                    out.println(rb.getString
1918
                        ("Certificate.chain.length.") + chain.length);
D
duke 已提交
1919 1920
                    for (int i = 0; i < chain.length; i ++) {
                        MessageFormat form = new MessageFormat
1921
                                (rb.getString("Certificate.i.1."));
D
duke 已提交
1922 1923 1924 1925 1926 1927 1928 1929 1930
                        Object[] source = {new Integer((i + 1))};
                        out.println(form.format(source));
                        if (verbose && (chain[i] instanceof X509Certificate)) {
                            printX509Cert((X509Certificate)(chain[i]), out);
                        } else if (debug) {
                            out.println(chain[i].toString());
                        } else {
                            dumpCert(chain[i], out);
                        }
1931
                        checkWeak(label, chain[i]);
D
duke 已提交
1932 1933 1934 1935
                    }
                } else {
                    // Print the digest of the user cert only
                    out.println
1936
                        (rb.getString("Certificate.fingerprint.SHA1.") +
1937
                        getCertFingerPrint("SHA1", chain[0]));
1938
                    checkWeak(label, chain[0]);
D
duke 已提交
1939 1940 1941 1942 1943 1944
                }
            }
        } else if (keyStore.entryInstanceOf(alias,
                KeyStore.TrustedCertificateEntry.class)) {
            // We have a trusted certificate entry
            Certificate cert = keyStore.getCertificate(alias);
1945 1946 1947
            Object[] source = {"trustedCertEntry"};
            String mf = new MessageFormat(
                    rb.getString("Entry.type.type.")).format(source) + "\n";
D
duke 已提交
1948
            if (verbose && (cert instanceof X509Certificate)) {
1949
                out.println(mf);
D
duke 已提交
1950 1951
                printX509Cert((X509Certificate)cert, out);
            } else if (rfc) {
1952
                out.println(mf);
D
duke 已提交
1953 1954 1955 1956
                dumpCert(cert, out);
            } else if (debug) {
                out.println(cert.toString());
            } else {
1957
                out.println("trustedCertEntry, ");
1958
                out.println(rb.getString("Certificate.fingerprint.SHA1.")
1959
                            + getCertFingerPrint("SHA1", cert));
D
duke 已提交
1960
            }
1961
            checkWeak(label, cert);
D
duke 已提交
1962
        } else {
1963
            out.println(rb.getString("Unknown.Entry.Type"));
D
duke 已提交
1964 1965 1966
        }
    }

1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
    boolean inplaceImportCheck() throws Exception {
        if (P11KEYSTORE.equalsIgnoreCase(srcstoretype) ||
                KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {
            return false;
        }

        if (srcksfname != null) {
            File srcksfile = new File(srcksfname);
            if (srcksfile.exists() && srcksfile.length() == 0) {
                throw new Exception(rb.getString
                        ("Source.keystore.file.exists.but.is.empty.") +
                        srcksfname);
            }
            if (srcksfile.getCanonicalFile()
                    .equals(new File(ksfname).getCanonicalFile())) {
                return true;
            } else {
                // Informational, especially if destkeystore is not
                // provided, which default to ~/.keystore.
                System.err.println(String.format(rb.getString(
                        "importing.keystore.status"), srcksfname, ksfname));
                return false;
            }
        } else {
            throw new Exception(rb.getString
                    ("Please.specify.srckeystore"));
        }
    }

D
duke 已提交
1996 1997 1998 1999 2000 2001 2002
    /**
     * Load the srckeystore from a stream, used in -importkeystore
     * @returns the src KeyStore
     */
    KeyStore loadSourceKeyStore() throws Exception {

        InputStream is = null;
2003
        File srcksfile = null;
D
duke 已提交
2004 2005 2006 2007 2008

        if (P11KEYSTORE.equalsIgnoreCase(srcstoretype) ||
                KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {
            if (!NONE.equals(srcksfname)) {
                System.err.println(MessageFormat.format(rb.getString
2009
                    (".keystore.must.be.NONE.if.storetype.is.{0}"), srcstoretype));
D
duke 已提交
2010 2011 2012 2013
                System.err.println();
                tinyHelp();
            }
        } else {
2014
            srcksfile = new File(srcksfname);
D
duke 已提交
2015 2016 2017 2018 2019
                is = new FileInputStream(srcksfile);
        }

        KeyStore store;
        try {
2020 2021 2022
            if (srcstoretype == null) {
                srcstoretype = KeyStore.getDefaultType();
            }
D
duke 已提交
2023 2024 2025 2026 2027 2028 2029 2030 2031
            if (srcProviderName == null) {
                store = KeyStore.getInstance(srcstoretype);
            } else {
                store = KeyStore.getInstance(srcstoretype, srcProviderName);
            }

            if (srcstorePass == null
                    && !srcprotectedPath
                    && !KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {
2032
                System.err.print(rb.getString("Enter.source.keystore.password."));
D
duke 已提交
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
                System.err.flush();
                srcstorePass = Password.readPassword(System.in);
                passwords.add(srcstorePass);
            }

            // always let keypass be storepass when using pkcs12
            if (P12KEYSTORE.equalsIgnoreCase(srcstoretype)) {
                if (srckeyPass != null && srcstorePass != null &&
                        !Arrays.equals(srcstorePass, srckeyPass)) {
                    MessageFormat form = new MessageFormat(rb.getString(
2043
                        "Warning.Different.store.and.key.passwords.not.supported.for.PKCS12.KeyStores.Ignoring.user.specified.command.value."));
D
duke 已提交
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
                    Object[] source = {"-srckeypass"};
                    System.err.println(form.format(source));
                    srckeyPass = srcstorePass;
                }
            }

            store.load(is, srcstorePass);   // "is" already null in PKCS11
        } finally {
            if (is != null) {
                is.close();
            }
        }

        if (srcstorePass == null
                && !KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {
2059
            // anti refactoring, copied from printNoIntegrityWarning(),
D
duke 已提交
2060 2061 2062
            // but change 2 lines
            System.err.println();
            System.err.println(rb.getString
2063
                (".WARNING.WARNING.WARNING."));
D
duke 已提交
2064
            System.err.println(rb.getString
2065
                (".The.integrity.of.the.information.stored.in.the.srckeystore."));
D
duke 已提交
2066
            System.err.println(rb.getString
2067
                (".WARNING.WARNING.WARNING."));
D
duke 已提交
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
            System.err.println();
        }

        return store;
    }

    /**
     * import all keys and certs from importkeystore.
     * keep alias unchanged if no name conflict, otherwise, prompt.
     * keep keypass unchanged for keys
     */
2079
    private void doImportKeyStore(KeyStore srcKS) throws Exception {
D
duke 已提交
2080 2081

        if (alias != null) {
2082
            doImportKeyStoreSingle(srcKS, alias);
D
duke 已提交
2083
        } else {
2084
            if (dest != null || srckeyPass != null) {
D
duke 已提交
2085
                throw new Exception(rb.getString(
2086
                        "if.alias.not.specified.destalias.and.srckeypass.must.not.be.specified"));
D
duke 已提交
2087
            }
2088
            doImportKeyStoreAll(srcKS);
D
duke 已提交
2089
        }
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104

        if (inplaceImport) {
            // Backup to file.old or file.old2...
            // The keystore is not rewritten yet now.
            for (int n = 1; /* forever */; n++) {
                inplaceBackupName = srcksfname + ".old" + (n == 1 ? "" : n);
                File bkFile = new File(inplaceBackupName);
                if (!bkFile.exists()) {
                    Files.copy(Paths.get(srcksfname), bkFile.toPath());
                    break;
                }
            }

        }

D
duke 已提交
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
        /*
         * Information display rule of -importkeystore
         * 1. inside single, shows failure
         * 2. inside all, shows sucess
         * 3. inside all where there is a failure, prompt for continue
         * 4. at the final of all, shows summary
         */
    }

    /**
     * Import a single entry named alias from srckeystore
     * @returns 1 if the import action succeed
     *          0 if user choose to ignore an alias-dumplicated entry
     *          2 if setEntry throws Exception
     */
    private int doImportKeyStoreSingle(KeyStore srckeystore, String alias)
            throws Exception {

        String newAlias = (dest==null) ? alias : dest;

        if (keyStore.containsAlias(newAlias)) {
            Object[] source = {alias};
            if (noprompt) {
                System.err.println(new MessageFormat(rb.getString(
2129
                        "Warning.Overwriting.existing.alias.alias.in.destination.keystore")).format(source));
D
duke 已提交
2130 2131
            } else {
                String reply = getYesNoReply(new MessageFormat(rb.getString(
2132
                        "Existing.entry.alias.alias.exists.overwrite.no.")).format(source));
D
duke 已提交
2133 2134
                if ("NO".equals(reply)) {
                    newAlias = inputStringFromStdin(rb.getString
2135
                            ("Enter.new.alias.name.RETURN.to.cancel.import.for.this.entry."));
D
duke 已提交
2136 2137
                    if ("".equals(newAlias)) {
                        System.err.println(new MessageFormat(rb.getString(
2138
                                "Entry.for.alias.alias.not.imported.")).format(
D
duke 已提交
2139 2140 2141 2142 2143 2144 2145
                                source));
                        return 0;
                    }
                }
            }
        }

2146 2147
        Pair<Entry,char[]> objs = recoverEntry(srckeystore, alias, srcstorePass, srckeyPass);
        Entry entry = objs.fst;
D
duke 已提交
2148 2149 2150 2151 2152 2153 2154

        PasswordProtection pp = null;

        // According to keytool.html, "The destination entry will be protected
        // using destkeypass. If destkeypass is not provided, the destination
        // entry will be protected with the source entry password."
        // so always try to protect with destKeyPass.
2155
        char[] newPass = null;
D
duke 已提交
2156
        if (destKeyPass != null) {
2157
            newPass = destKeyPass;
D
duke 已提交
2158
            pp = new PasswordProtection(destKeyPass);
2159
        } else if (objs.snd != null) {
2160
            newPass = objs.snd;
2161
            pp = new PasswordProtection(objs.snd);
D
duke 已提交
2162 2163 2164
        }

        try {
2165 2166 2167 2168
            Certificate c = srckeystore.getCertificate(alias);
            if (c != null) {
                checkWeak("<" + newAlias + ">", c);
            }
D
duke 已提交
2169
            keyStore.setEntry(newAlias, entry, pp);
2170 2171 2172 2173 2174 2175 2176 2177
            // Place the check so that only successful imports are blocked.
            // For example, we don't block a failed SecretEntry import.
            if (P12KEYSTORE.equalsIgnoreCase(storetype)) {
                if (newPass != null && !Arrays.equals(newPass, storePass)) {
                    throw new Exception(rb.getString(
                            "The.destination.pkcs12.keystore.has.different.storepass.and.keypass.Please.retry.with.destkeypass.specified."));
                }
            }
D
duke 已提交
2178 2179 2180 2181
            return 1;
        } catch (KeyStoreException kse) {
            Object[] source2 = {alias, kse.toString()};
            MessageFormat form = new MessageFormat(rb.getString(
2182
                    "Problem.importing.entry.for.alias.alias.exception.Entry.for.alias.alias.not.imported."));
D
duke 已提交
2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
            System.err.println(form.format(source2));
            return 2;
        }
    }

    private void doImportKeyStoreAll(KeyStore srckeystore) throws Exception {

        int ok = 0;
        int count = srckeystore.size();
        for (Enumeration<String> e = srckeystore.aliases();
                                        e.hasMoreElements(); ) {
            String alias = e.nextElement();
            int result = doImportKeyStoreSingle(srckeystore, alias);
            if (result == 1) {
                ok++;
                Object[] source = {alias};
2199
                MessageFormat form = new MessageFormat(rb.getString("Entry.for.alias.alias.successfully.imported."));
D
duke 已提交
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
                System.err.println(form.format(source));
            } else if (result == 2) {
                if (!noprompt) {
                    String reply = getYesNoReply("Do you want to quit the import process? [no]:  ");
                    if ("YES".equals(reply)) {
                        break;
                    }
                }
            }
        }
        Object[] source = {ok, count-ok};
        MessageFormat form = new MessageFormat(rb.getString(
2212
                "Import.command.completed.ok.entries.successfully.imported.fail.entries.failed.or.cancelled"));
D
duke 已提交
2213 2214 2215 2216 2217 2218 2219 2220 2221
        System.err.println(form.format(source));
    }

    /**
     * Prints all keystore entries.
     */
    private void doPrintEntries(PrintStream out)
        throws Exception
    {
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
        // Adjust displayed keystore type if needed.
        String keystoreTypeToPrint = keyStore.getType();
        if ("JKS".equalsIgnoreCase(keystoreTypeToPrint)) {
            if (ksfile != null && ksfile.exists()) {
                String realType = keyStoreType(ksfile);
                // If the magic number does not conform to JKS
                // then it must be PKCS12
                if (!"JKS".equalsIgnoreCase(realType)) {
                    keystoreTypeToPrint = P12KEYSTORE;
                }
            }
        }
        out.println(rb.getString("Keystore.type.") + keystoreTypeToPrint);
2235
        out.println(rb.getString("Keystore.provider.") +
D
duke 已提交
2236 2237 2238 2239 2240 2241
                keyStore.getProvider().getName());
        out.println();

        MessageFormat form;
        form = (keyStore.size() == 1) ?
                new MessageFormat(rb.getString
2242
                        ("Your.keystore.contains.keyStore.size.entry")) :
D
duke 已提交
2243
                new MessageFormat(rb.getString
2244
                        ("Your.keystore.contains.keyStore.size.entries"));
D
duke 已提交
2245 2246 2247 2248 2249 2250 2251
        Object[] source = {new Integer(keyStore.size())};
        out.println(form.format(source));
        out.println();

        for (Enumeration<String> e = keyStore.aliases();
                                        e.hasMoreElements(); ) {
            String alias = e.nextElement();
2252
            doPrintEntry("<" + alias + ">", alias, out);
D
duke 已提交
2253
            if (verbose || rfc) {
2254
                out.println(rb.getString("NEWLINE"));
D
duke 已提交
2255
                out.println(rb.getString
2256
                        ("STAR"));
D
duke 已提交
2257
                out.println(rb.getString
2258
                        ("STARNN"));
D
duke 已提交
2259 2260 2261 2262
            }
        }
    }

2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334
    private static <T> Iterable<T> e2i(final Enumeration<T> e) {
        return new Iterable<T>() {
            @Override
            public Iterator<T> iterator() {
                return new Iterator<T>() {
                    @Override
                    public boolean hasNext() {
                        return e.hasMoreElements();
                    }
                    @Override
                    public T next() {
                        return e.nextElement();
                    }
                    public void remove() {
                        throw new UnsupportedOperationException("Not supported yet.");
                    }
                };
            }
        };
    }

    /**
     * Loads CRLs from a source. This method is also called in JarSigner.
     * @param src the source, which means System.in if null, or a URI,
     *        or a bare file path name
     */
    public static Collection<? extends CRL> loadCRLs(String src) throws Exception {
        InputStream in = null;
        URI uri = null;
        if (src == null) {
            in = System.in;
        } else {
            try {
                uri = new URI(src);
                if (uri.getScheme().equals("ldap")) {
                    // No input stream for LDAP
                } else {
                    in = uri.toURL().openStream();
                }
            } catch (Exception e) {
                try {
                    in = new FileInputStream(src);
                } catch (Exception e2) {
                    if (uri == null || uri.getScheme() == null) {
                        throw e2;   // More likely a bare file path
                    } else {
                        throw e;    // More likely a protocol or network problem
                    }
                }
            }
        }
        if (in != null) {
            try {
                // Read the full stream before feeding to X509Factory,
                // otherwise, keytool -gencrl | keytool -printcrl
                // might not work properly, since -gencrl is slow
                // and there's no data in the pipe at the beginning.
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                byte[] b = new byte[4096];
                while (true) {
                    int len = in.read(b);
                    if (len < 0) break;
                    bout.write(b, 0, len);
                }
                return CertificateFactory.getInstance("X509").generateCRLs(
                        new ByteArrayInputStream(bout.toByteArray()));
            } finally {
                if (in != System.in) {
                    in.close();
                }
            }
        } else {    // must be LDAP, and uri is not null
2335 2336
            // Lazily load LDAPCertStoreHelper if present
            CertStoreHelper helper = CertStoreHelper.getInstance("LDAP");
2337 2338
            String path = uri.getPath();
            if (path.charAt(0) == '/') path = path.substring(1);
2339
            CertStore s = helper.getCertStore(uri);
2340
            X509CRLSelector sel =
2341
                    helper.wrap(new X509CRLSelector(), null, path);
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
            return s.getCRLs(sel);
        }
    }

    /**
     * Returns CRLs described in a X509Certificate's CRLDistributionPoints
     * Extension. Only those containing a general name of type URI are read.
     */
    public static List<CRL> readCRLsFromCert(X509Certificate cert)
            throws Exception {
2352
        List<CRL> crls = new ArrayList<>();
2353 2354 2355
        CRLDistributionPointsExtension ext =
                X509CertImpl.toImpl(cert).getCRLDistributionPointsExtension();
        if (ext == null) return crls;
2356 2357 2358
        List<DistributionPoint> distPoints =
                ext.get(CRLDistributionPointsExtension.POINTS);
        for (DistributionPoint o: distPoints) {
2359 2360 2361 2362 2363
            GeneralNames names = o.getFullName();
            if (names != null) {
                for (GeneralName name: names.names()) {
                    if (name.getType() == GeneralNameInterface.NAME_URI) {
                        URIName uriName = (URIName)name.getName();
2364
                        for (CRL crl: loadCRLs(uriName.getName())) {
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401
                            if (crl instanceof X509CRL) {
                                crls.add((X509CRL)crl);
                            }
                        }
                        break;  // Different name should point to same CRL
                    }
                }
            }
        }
        return crls;
    }

    private static String verifyCRL(KeyStore ks, CRL crl)
            throws Exception {
        X509CRLImpl xcrl = (X509CRLImpl)crl;
        X500Principal issuer = xcrl.getIssuerX500Principal();
        for (String s: e2i(ks.aliases())) {
            Certificate cert = ks.getCertificate(s);
            if (cert instanceof X509Certificate) {
                X509Certificate xcert = (X509Certificate)cert;
                if (xcert.getSubjectX500Principal().equals(issuer)) {
                    try {
                        ((X509CRLImpl)crl).verify(cert.getPublicKey());
                        return s;
                    } catch (Exception e) {
                    }
                }
            }
        }
        return null;
    }

    private void doPrintCRL(String src, PrintStream out)
            throws Exception {
        for (CRL crl: loadCRLs(src)) {
            printCRL(crl, out);
            String issuer = null;
2402
            Certificate signer = null;
2403 2404 2405
            if (caks != null) {
                issuer = verifyCRL(caks, crl);
                if (issuer != null) {
2406
                    signer = caks.getCertificate(issuer);
2407
                    out.printf(rb.getString(
2408 2409 2410 2411
                            "verified.by.s.in.s.weak"),
                            issuer,
                            "cacerts",
                            withWeak(signer.getPublicKey()));
2412
                    out.println();
2413 2414 2415 2416 2417
                }
            }
            if (issuer == null && keyStore != null) {
                issuer = verifyCRL(keyStore, crl);
                if (issuer != null) {
2418
                    signer = keyStore.getCertificate(issuer);
2419
                    out.printf(rb.getString(
2420 2421 2422 2423
                            "verified.by.s.in.s.weak"),
                            issuer,
                            "keystore",
                            withWeak(signer.getPublicKey()));
2424
                    out.println();
2425 2426 2427 2428
                }
            }
            if (issuer == null) {
                out.println(rb.getString
2429
                        ("STAR"));
2430 2431
                out.println(rb.getString
                        ("warning.not.verified.make.sure.keystore.is.correct"));
2432
                out.println(rb.getString
2433
                        ("STARNN"));
2434
            }
2435
            checkWeak(rb.getString("the.crl"), crl, signer == null ? null : signer.getPublicKey());
2436 2437 2438 2439 2440
        }
    }

    private void printCRL(CRL crl, PrintStream out)
            throws Exception {
2441
        X509CRL xcrl = (X509CRL)crl;
2442 2443
        if (rfc) {
            out.println("-----BEGIN X509 CRL-----");
2444
            out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(xcrl.getEncoded()));
2445 2446
            out.println("-----END X509 CRL-----");
        } else {
2447 2448 2449 2450 2451 2452 2453 2454
            String s;
            if (crl instanceof X509CRLImpl) {
                X509CRLImpl x509crl = (X509CRLImpl) crl;
                s = x509crl.toStringWithAlgName(withWeak("" + x509crl.getSigAlgId()));
            } else {
                s = crl.toString();
            }
            out.println(s);
2455 2456 2457
        }
    }

2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
    private void doPrintCertReq(InputStream in, PrintStream out)
            throws Exception {

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuffer sb = new StringBuffer();
        boolean started = false;
        while (true) {
            String s = reader.readLine();
            if (s == null) break;
            if (!started) {
                if (s.startsWith("-----")) {
                    started = true;
                }
            } else {
                if (s.startsWith("-----")) {
                    break;
                }
                sb.append(s);
            }
        }
2478
        PKCS10 req = new PKCS10(Pem.decode(new String(sb)));
2479 2480

        PublicKey pkey = req.getSubjectPublicKeyInfo();
2481 2482 2483 2484 2485
        out.printf(rb.getString("PKCS.10.with.weak"),
                req.getSubjectName(),
                pkey.getFormat(),
                withWeak(pkey),
                withWeak(req.getSigAlg()));
2486 2487
        for (PKCS10Attribute attr: req.getAttributes().getAttributes()) {
            ObjectIdentifier oid = attr.getAttributeId();
2488
            if (oid.equals((Object)PKCS9Attribute.EXTENSION_REQUEST_OID)) {
2489
                CertificateExtensions exts = (CertificateExtensions)attr.getAttributeValue();
2490
                if (exts != null) {
2491
                    printExtensions(rb.getString("Extension.Request."), exts, out);
2492
                }
2493
            } else {
2494 2495 2496 2497 2498 2499 2500 2501 2502
                out.println("Attribute: " + attr.getAttributeId());
                PKCS9Attribute pkcs9Attr =
                        new PKCS9Attribute(attr.getAttributeId(),
                                           attr.getAttributeValue());
                out.print(pkcs9Attr.getName() + ": ");
                Object attrVal = attr.getAttributeValue();
                out.println(attrVal instanceof String[] ?
                            Arrays.toString((String[]) attrVal) :
                            attrVal);
2503 2504 2505 2506 2507
            }
        }
        if (debug) {
            out.println(req);   // Just to see more, say, public key length...
        }
2508
        checkWeak(rb.getString("the.certificate.request"), req);
2509 2510
    }

D
duke 已提交
2511 2512
    /**
     * Reads a certificate (or certificate chain) and prints its contents in
2513
     * a human readable format.
D
duke 已提交
2514
     */
2515
    private void printCertFromStream(InputStream in, PrintStream out)
D
duke 已提交
2516 2517 2518 2519 2520 2521
        throws Exception
    {
        Collection<? extends Certificate> c = null;
        try {
            c = cf.generateCertificates(in);
        } catch (CertificateException ce) {
2522
            throw new Exception(rb.getString("Failed.to.parse.input"), ce);
D
duke 已提交
2523 2524
        }
        if (c.isEmpty()) {
2525
            throw new Exception(rb.getString("Empty.input"));
D
duke 已提交
2526 2527 2528 2529 2530 2531 2532
        }
        Certificate[] certs = c.toArray(new Certificate[c.size()]);
        for (int i=0; i<certs.length; i++) {
            X509Certificate x509Cert = null;
            try {
                x509Cert = (X509Certificate)certs[i];
            } catch (ClassCastException cce) {
2533
                throw new Exception(rb.getString("Not.X.509.certificate"));
D
duke 已提交
2534 2535 2536
            }
            if (certs.length > 1) {
                MessageFormat form = new MessageFormat
2537
                        (rb.getString("Certificate.i.1."));
D
duke 已提交
2538 2539 2540
                Object[] source = {new Integer(i + 1)};
                out.println(form.format(source));
            }
2541 2542 2543 2544
            if (rfc)
                dumpCert(x509Cert, out);
            else
                printX509Cert(x509Cert, out);
D
duke 已提交
2545 2546 2547
            if (i < (certs.length-1)) {
                out.println();
            }
2548 2549 2550 2551 2552 2553 2554 2555 2556
            checkWeak(oneInMany(rb.getString("the.certificate"), i, certs.length), x509Cert);
        }
    }

    private static String oneInMany(String label, int i, int num) {
        if (num == 1) {
            return label;
        } else {
            return String.format(rb.getString("one.in.many"), label, i+1, num);
D
duke 已提交
2557 2558 2559
        }
    }

2560
    private void doPrintCert(final PrintStream out) throws Exception {
2561 2562 2563
        if (jarfile != null) {
            JarFile jf = new JarFile(jarfile, true);
            Enumeration<JarEntry> entries = jf.entries();
2564
            Set<CodeSigner> ss = new HashSet<>();
2565 2566 2567 2568
            byte[] buffer = new byte[8192];
            int pos = 0;
            while (entries.hasMoreElements()) {
                JarEntry je = entries.nextElement();
2569
                try (InputStream is = jf.getInputStream(je)) {
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
                    while (is.read(buffer) != -1) {
                        // we just read. this will throw a SecurityException
                        // if a signature/digest check fails. This also
                        // populate the signers
                    }
                }
                CodeSigner[] signers = je.getCodeSigners();
                if (signers != null) {
                    for (CodeSigner signer: signers) {
                        if (!ss.contains(signer)) {
                            ss.add(signer);
2581
                            out.printf(rb.getString("Signer.d."), ++pos);
2582 2583
                            out.println();
                            out.println();
2584
                            out.println(rb.getString("Signature."));
2585
                            out.println();
2586 2587 2588 2589 2590

                            List<? extends Certificate> certs
                                    = signer.getSignerCertPath().getCertificates();
                            int cc = 0;
                            for (Certificate cert: certs) {
2591 2592
                                X509Certificate x = (X509Certificate)cert;
                                if (rfc) {
2593
                                    out.println(rb.getString("Certificate.owner.") + x.getSubjectDN() + "\n");
2594 2595 2596 2597 2598
                                    dumpCert(x, out);
                                } else {
                                    printX509Cert(x, out);
                                }
                                out.println();
2599
                                checkWeak(oneInMany(rb.getString("the.certificate"), cc++, certs.size()), x);
2600 2601 2602
                            }
                            Timestamp ts = signer.getTimestamp();
                            if (ts != null) {
2603
                                out.println(rb.getString("Timestamp."));
2604
                                out.println();
2605 2606 2607
                                certs = ts.getSignerCertPath().getCertificates();
                                cc = 0;
                                for (Certificate cert: certs) {
2608 2609
                                    X509Certificate x = (X509Certificate)cert;
                                    if (rfc) {
2610
                                        out.println(rb.getString("Certificate.owner.") + x.getSubjectDN() + "\n");
2611 2612 2613 2614 2615
                                        dumpCert(x, out);
                                    } else {
                                        printX509Cert(x, out);
                                    }
                                    out.println();
2616
                                    checkWeak(oneInMany(rb.getString("the.tsa.certificate"), cc++, certs.size()), x);
2617 2618 2619 2620 2621 2622 2623
                                }
                            }
                        }
                    }
                }
            }
            jf.close();
2624
            if (ss.isEmpty()) {
2625
                out.println(rb.getString("Not.a.signed.jar.file"));
2626 2627
            }
        } else if (sslserver != null) {
2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648
            // Lazily load SSLCertStoreHelper if present
            CertStoreHelper helper = CertStoreHelper.getInstance("SSLServer");
            CertStore cs = helper.getCertStore(new URI("https://" + sslserver));
            Collection<? extends Certificate> chain;
            try {
                chain = cs.getCertificates(null);
                if (chain.isEmpty()) {
                    // If the certs are not retrieved, we consider it an error
                    // even if the URL connection is successful.
                    throw new Exception(rb.getString(
                                        "No.certificate.from.the.SSL.server"));
                }
            } catch (CertStoreException cse) {
                if (cse.getCause() instanceof IOException) {
                    throw new Exception(rb.getString(
                                        "No.certificate.from.the.SSL.server"),
                                        cse.getCause());
                } else {
                    throw cse;
                }
            }
2649

2650 2651 2652 2653 2654 2655
            int i = 0;
            for (Certificate cert : chain) {
                try {
                    if (rfc) {
                        dumpCert(cert, out);
                    } else {
2656
                        out.println("Certificate #" + i);
2657 2658 2659
                        out.println("====================================");
                        printX509Cert((X509Certificate)cert, out);
                        out.println();
2660
                    }
2661
                    checkWeak(oneInMany(rb.getString("the.certificate"), i++, chain.size()), cert);
2662 2663 2664
                } catch (Exception e) {
                    if (debug) {
                        e.printStackTrace();
2665 2666 2667 2668 2669
                    }
                }
            }
        } else {
            if (filename != null) {
2670 2671
                try (FileInputStream inStream = new FileInputStream(filename)) {
                    printCertFromStream(inStream, out);
2672
                }
2673 2674
            } else {
                printCertFromStream(System.in, out);
2675 2676 2677
            }
        }
    }
D
duke 已提交
2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
    /**
     * Creates a self-signed certificate, and stores it as a single-element
     * certificate chain.
     */
    private void doSelfCert(String alias, String dname, String sigAlgName)
        throws Exception
    {
        if (alias == null) {
            alias = keyAlias;
        }

2689 2690
        Pair<Key,char[]> objs = recoverKey(alias, storePass, keyPass);
        PrivateKey privKey = (PrivateKey)objs.fst;
D
duke 已提交
2691
        if (keyPass == null)
2692
            keyPass = objs.snd;
D
duke 已提交
2693 2694 2695

        // Determine the signature algorithm
        if (sigAlgName == null) {
2696
            sigAlgName = getCompatibleSigAlgName(privKey.getAlgorithm());
D
duke 已提交
2697 2698 2699 2700 2701 2702
        }

        // Get the old certificate
        Certificate oldCert = keyStore.getCertificate(alias);
        if (oldCert == null) {
            MessageFormat form = new MessageFormat
2703
                (rb.getString("alias.has.no.public.key"));
D
duke 已提交
2704 2705 2706 2707 2708
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }
        if (!(oldCert instanceof X509Certificate)) {
            MessageFormat form = new MessageFormat
2709
                (rb.getString("alias.has.no.X.509.certificate"));
D
duke 已提交
2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }

        // convert to X509CertImpl, so that we can modify selected fields
        // (no public APIs available yet)
        byte[] encoded = oldCert.getEncoded();
        X509CertImpl certImpl = new X509CertImpl(encoded);
        X509CertInfo certInfo = (X509CertInfo)certImpl.get(X509CertImpl.NAME
                                                           + "." +
                                                           X509CertImpl.INFO);

        // Extend its validity
        Date firstDate = getStartDate(startDate);
        Date lastDate = new Date();
        lastDate.setTime(firstDate.getTime() + validity*1000L*24L*60L*60L);
        CertificateValidity interval = new CertificateValidity(firstDate,
                                                               lastDate);
        certInfo.set(X509CertInfo.VALIDITY, interval);

        // Make new serial number
2731 2732
        certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
                    new java.util.Random().nextInt() & 0x7fffffff));
D
duke 已提交
2733 2734 2735 2736 2737 2738

        // Set owner and issuer fields
        X500Name owner;
        if (dname == null) {
            // Get the owner name from the certificate
            owner = (X500Name)certInfo.get(X509CertInfo.SUBJECT + "." +
2739
                                           X509CertInfo.DN_NAME);
D
duke 已提交
2740 2741 2742 2743
        } else {
            // Use the owner name specified at the command line
            owner = new X500Name(dname);
            certInfo.set(X509CertInfo.SUBJECT + "." +
2744
                         X509CertInfo.DN_NAME, owner);
D
duke 已提交
2745 2746 2747
        }
        // Make issuer same as owner (self-signed!)
        certInfo.set(X509CertInfo.ISSUER + "." +
2748
                     X509CertInfo.DN_NAME, owner);
D
duke 已提交
2749 2750 2751 2752 2753 2754

        // The inner and outer signature algorithms have to match.
        // The way we achieve that is really ugly, but there seems to be no
        // other solution: We first sign the cert, then retrieve the
        // outer sigalg and use it to set the inner sigalg
        X509CertImpl newCert = new X509CertImpl(certInfo);
2755 2756 2757
        AlgorithmParameterSpec params = AlgorithmId
                .getDefaultAlgorithmParameterSpec(sigAlgName, privKey);
        newCert.sign(privKey, params, sigAlgName, null);
D
duke 已提交
2758 2759 2760 2761 2762 2763 2764
        AlgorithmId sigAlgid = (AlgorithmId)newCert.get(X509CertImpl.SIG_ALG);
        certInfo.set(CertificateAlgorithmId.NAME + "." +
                     CertificateAlgorithmId.ALGORITHM, sigAlgid);

        certInfo.set(X509CertInfo.VERSION,
                        new CertificateVersion(CertificateVersion.V3));

2765 2766 2767 2768 2769 2770 2771
        CertificateExtensions ext = createV3Extensions(
                null,
                (CertificateExtensions)certInfo.get(X509CertInfo.EXTENSIONS),
                v3ext,
                oldCert.getPublicKey(),
                null);
        certInfo.set(X509CertInfo.EXTENSIONS, ext);
D
duke 已提交
2772 2773
        // Sign the new certificate
        newCert = new X509CertImpl(certInfo);
2774
        newCert.sign(privKey, params, sigAlgName, null);
D
duke 已提交
2775 2776 2777 2778 2779 2780 2781

        // Store the new certificate as a single-element certificate chain
        keyStore.setKeyEntry(alias, privKey,
                             (keyPass != null) ? keyPass : storePass,
                             new Certificate[] { newCert } );

        if (verbose) {
2782
            System.err.println(rb.getString("New.certificate.self.signed."));
D
duke 已提交
2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808
            System.err.print(newCert.toString());
            System.err.println();
        }
    }

    /**
     * Processes a certificate reply from a certificate authority.
     *
     * <p>Builds a certificate chain on top of the certificate reply,
     * using trusted certificates from the keystore. The chain is complete
     * after a self-signed certificate has been encountered. The self-signed
     * certificate is considered a root certificate authority, and is stored
     * at the end of the chain.
     *
     * <p>The newly generated chain replaces the old chain associated with the
     * key entry.
     *
     * @return true if the certificate reply was installed, otherwise false.
     */
    private boolean installReply(String alias, InputStream in)
        throws Exception
    {
        if (alias == null) {
            alias = keyAlias;
        }

2809 2810
        Pair<Key,char[]> objs = recoverKey(alias, storePass, keyPass);
        PrivateKey privKey = (PrivateKey)objs.fst;
D
duke 已提交
2811
        if (keyPass == null) {
2812
            keyPass = objs.snd;
D
duke 已提交
2813 2814 2815 2816 2817
        }

        Certificate userCert = keyStore.getCertificate(alias);
        if (userCert == null) {
            MessageFormat form = new MessageFormat
2818
                (rb.getString("alias.has.no.public.key.certificate."));
D
duke 已提交
2819 2820 2821 2822 2823 2824 2825
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }

        // Read the certificates in the reply
        Collection<? extends Certificate> c = cf.generateCertificates(in);
        if (c.isEmpty()) {
2826
            throw new Exception(rb.getString("Reply.has.no.certificates"));
D
duke 已提交
2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
        }
        Certificate[] replyCerts = c.toArray(new Certificate[c.size()]);
        Certificate[] newChain;
        if (replyCerts.length == 1) {
            // single-cert reply
            newChain = establishCertChain(userCert, replyCerts[0]);
        } else {
            // cert-chain reply (e.g., PKCS#7)
            newChain = validateReply(alias, userCert, replyCerts);
        }

        // Now store the newly established chain in the keystore. The new
2839
        // chain replaces the old one. The chain can be null if user chooses no.
D
duke 已提交
2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858
        if (newChain != null) {
            keyStore.setKeyEntry(alias, privKey,
                                 (keyPass != null) ? keyPass : storePass,
                                 newChain);
            return true;
        } else {
            return false;
        }
    }

    /**
     * Imports a certificate and adds it to the list of trusted certificates.
     *
     * @return true if the certificate was added, otherwise false.
     */
    private boolean addTrustedCert(String alias, InputStream in)
        throws Exception
    {
        if (alias == null) {
2859
            throw new Exception(rb.getString("Must.specify.alias"));
D
duke 已提交
2860 2861 2862
        }
        if (keyStore.containsAlias(alias)) {
            MessageFormat form = new MessageFormat(rb.getString
2863
                ("Certificate.not.imported.alias.alias.already.exists"));
D
duke 已提交
2864 2865 2866 2867 2868 2869 2870 2871
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }

        // Read the certificate
        X509Certificate cert = null;
        try {
            cert = (X509Certificate)cf.generateCertificate(in);
2872
        } catch (ClassCastException | CertificateException ce) {
2873
            throw new Exception(rb.getString("Input.not.an.X.509.certificate"));
D
duke 已提交
2874 2875
        }

2876 2877
        if (noprompt) {
            checkWeak(rb.getString("the.input"), cert);
2878
            keyStore.setCertificateEntry(alias, cert);
2879 2880 2881
            return true;
        }

D
duke 已提交
2882 2883
        // if certificate is self-signed, make sure it verifies
        boolean selfSigned = false;
2884
        if (KeyStoreUtil.isSelfSigned(cert)) {
D
duke 已提交
2885 2886 2887 2888 2889 2890 2891 2892 2893
            cert.verify(cert.getPublicKey());
            selfSigned = true;
        }

        // check if cert already exists in keystore
        String reply = null;
        String trustalias = keyStore.getCertificateAlias(cert);
        if (trustalias != null) {
            MessageFormat form = new MessageFormat(rb.getString
2894
                ("Certificate.already.exists.in.keystore.under.alias.trustalias."));
D
duke 已提交
2895 2896
            Object[] source = {trustalias};
            System.err.println(form.format(source));
2897 2898
            checkWeak(rb.getString("the.input"), cert);
            printWeakWarnings(true);
D
duke 已提交
2899
            reply = getYesNoReply
2900
                (rb.getString("Do.you.still.want.to.add.it.no."));
D
duke 已提交
2901 2902 2903 2904
        } else if (selfSigned) {
            if (trustcacerts && (caks != null) &&
                    ((trustalias=caks.getCertificateAlias(cert)) != null)) {
                MessageFormat form = new MessageFormat(rb.getString
2905
                        ("Certificate.already.exists.in.system.wide.CA.keystore.under.alias.trustalias."));
D
duke 已提交
2906 2907
                Object[] source = {trustalias};
                System.err.println(form.format(source));
2908 2909
                checkWeak(rb.getString("the.input"), cert);
                printWeakWarnings(true);
D
duke 已提交
2910
                reply = getYesNoReply
2911
                        (rb.getString("Do.you.still.want.to.add.it.to.your.own.keystore.no."));
D
duke 已提交
2912 2913 2914 2915 2916
            }
            if (trustalias == null) {
                // Print the cert and ask user if they really want to add
                // it to their keystore
                printX509Cert(cert, System.out);
2917 2918
                checkWeak(rb.getString("the.input"), cert);
                printWeakWarnings(true);
D
duke 已提交
2919
                reply = getYesNoReply
2920
                        (rb.getString("Trust.this.certificate.no."));
D
duke 已提交
2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931
            }
        }
        if (reply != null) {
            if ("YES".equals(reply)) {
                keyStore.setCertificateEntry(alias, cert);
                return true;
            } else {
                return false;
            }
        }

2932
        // Not found in this keystore and not self-signed
D
duke 已提交
2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943
        // Try to establish trust chain
        try {
            Certificate[] chain = establishCertChain(null, cert);
            if (chain != null) {
                keyStore.setCertificateEntry(alias, cert);
                return true;
            }
        } catch (Exception e) {
            // Print the cert and ask user if they really want to add it to
            // their keystore
            printX509Cert(cert, System.out);
2944 2945
            checkWeak(rb.getString("the.input"), cert);
            printWeakWarnings(true);
D
duke 已提交
2946
            reply = getYesNoReply
2947
                (rb.getString("Trust.this.certificate.no."));
D
duke 已提交
2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973
            if ("YES".equals(reply)) {
                keyStore.setCertificateEntry(alias, cert);
                return true;
            } else {
                return false;
            }
        }

        return false;
    }

    /**
     * Prompts user for new password. New password must be different from
     * old one.
     *
     * @param prompt the message that gets prompted on the screen
     * @param oldPasswd the current (i.e., old) password
     */
    private char[] getNewPasswd(String prompt, char[] oldPasswd)
        throws Exception
    {
        char[] entered = null;
        char[] reentered = null;

        for (int count = 0; count < 3; count++) {
            MessageFormat form = new MessageFormat
2974
                (rb.getString("New.prompt."));
D
duke 已提交
2975 2976 2977 2978 2979 2980
            Object[] source = {prompt};
            System.err.print(form.format(source));
            entered = Password.readPassword(System.in);
            passwords.add(entered);
            if (entered == null || entered.length < 6) {
                System.err.println(rb.getString
2981
                    ("Password.is.too.short.must.be.at.least.6.characters"));
D
duke 已提交
2982
            } else if (Arrays.equals(entered, oldPasswd)) {
2983
                System.err.println(rb.getString("Passwords.must.differ"));
D
duke 已提交
2984 2985
            } else {
                form = new MessageFormat
2986
                        (rb.getString("Re.enter.new.prompt."));
D
duke 已提交
2987 2988 2989 2990 2991 2992
                Object[] src = {prompt};
                System.err.print(form.format(src));
                reentered = Password.readPassword(System.in);
                passwords.add(reentered);
                if (!Arrays.equals(entered, reentered)) {
                    System.err.println
2993
                        (rb.getString("They.don.t.match.Try.again"));
D
duke 已提交
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007
                } else {
                    Arrays.fill(reentered, ' ');
                    return entered;
                }
            }
            if (entered != null) {
                Arrays.fill(entered, ' ');
                entered = null;
            }
            if (reentered != null) {
                Arrays.fill(reentered, ' ');
                reentered = null;
            }
        }
3008
        throw new Exception(rb.getString("Too.many.failures.try.later"));
D
duke 已提交
3009 3010 3011 3012 3013 3014 3015 3016 3017 3018
    }

    /**
     * Prompts user for alias name.
     * @param prompt the {0} of "Enter {0} alias name:  " in prompt line
     * @returns the string entered by the user, without the \n at the end
     */
    private String getAlias(String prompt) throws Exception {
        if (prompt != null) {
            MessageFormat form = new MessageFormat
3019
                (rb.getString("Enter.prompt.alias.name."));
D
duke 已提交
3020 3021 3022
            Object[] source = {prompt};
            System.err.print(form.format(source));
        } else {
3023
            System.err.print(rb.getString("Enter.alias.name."));
D
duke 已提交
3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053
        }
        return (new BufferedReader(new InputStreamReader(
                                        System.in))).readLine();
    }

    /**
     * Prompts user for an input string from the command line (System.in)
     * @prompt the prompt string printed
     * @returns the string entered by the user, without the \n at the end
     */
    private String inputStringFromStdin(String prompt) throws Exception {
        System.err.print(prompt);
        return (new BufferedReader(new InputStreamReader(
                                        System.in))).readLine();
    }

    /**
     * Prompts user for key password. User may select to choose the same
     * password (<code>otherKeyPass</code>) as for <code>otherAlias</code>.
     */
    private char[] getKeyPasswd(String alias, String otherAlias,
                                char[] otherKeyPass)
        throws Exception
    {
        int count = 0;
        char[] keyPass = null;

        do {
            if (otherKeyPass != null) {
                MessageFormat form = new MessageFormat(rb.getString
3054
                        ("Enter.key.password.for.alias."));
D
duke 已提交
3055 3056 3057 3058
                Object[] source = {alias};
                System.err.println(form.format(source));

                form = new MessageFormat(rb.getString
3059
                        (".RETURN.if.same.as.for.otherAlias."));
D
duke 已提交
3060 3061 3062 3063
                Object[] src = {otherAlias};
                System.err.print(form.format(src));
            } else {
                MessageFormat form = new MessageFormat(rb.getString
3064
                        ("Enter.key.password.for.alias."));
D
duke 已提交
3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077
                Object[] source = {alias};
                System.err.print(form.format(source));
            }
            System.err.flush();
            keyPass = Password.readPassword(System.in);
            passwords.add(keyPass);
            if (keyPass == null) {
                keyPass = otherKeyPass;
            }
            count++;
        } while ((keyPass == null) && count < 3);

        if (keyPass == null) {
3078
            throw new Exception(rb.getString("Too.many.failures.try.later"));
D
duke 已提交
3079 3080 3081 3082 3083
        }

        return keyPass;
    }

3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101
    private String withWeak(String alg) {
        if (DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, alg, null)) {
            return alg;
        } else {
            return String.format(rb.getString("with.weak"), alg);
        }
    }

    private String withWeak(PublicKey key) {
        if (DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) {
            return String.format(rb.getString("key.bit"),
                    KeyUtil.getKeySize(key), key.getAlgorithm());
        } else {
            return String.format(rb.getString("key.bit.weak"),
                    KeyUtil.getKeySize(key), key.getAlgorithm());
        }
    }

D
duke 已提交
3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126
    /**
     * Prints a certificate in a human readable format.
     */
    private void printX509Cert(X509Certificate cert, PrintStream out)
        throws Exception
    {
        /*
        out.println("Owner: "
                    + cert.getSubjectDN().toString()
                    + "\n"
                    + "Issuer: "
                    + cert.getIssuerDN().toString()
                    + "\n"
                    + "Serial number: " + cert.getSerialNumber().toString(16)
                    + "\n"
                    + "Valid from: " + cert.getNotBefore().toString()
                    + " until: " + cert.getNotAfter().toString()
                    + "\n"
                    + "Certificate fingerprints:\n"
                    + "\t MD5:  " + getCertFingerPrint("MD5", cert)
                    + "\n"
                    + "\t SHA1: " + getCertFingerPrint("SHA1", cert));
        */

        MessageFormat form = new MessageFormat
3127
                (rb.getString(".PATTERN.printX509Cert.with.weak"));
3128
        PublicKey pkey = cert.getPublicKey();
3129 3130 3131 3132 3133
        String sigName = cert.getSigAlgName();
        // No need to warn about sigalg of a trust anchor
        if (!isTrustedCert(cert)) {
            sigName = withWeak(sigName);
        }
D
duke 已提交
3134 3135 3136 3137 3138 3139 3140
        Object[] source = {cert.getSubjectDN().toString(),
                        cert.getIssuerDN().toString(),
                        cert.getSerialNumber().toString(16),
                        cert.getNotBefore().toString(),
                        cert.getNotAfter().toString(),
                        getCertFingerPrint("MD5", cert),
                        getCertFingerPrint("SHA1", cert),
3141
                        getCertFingerPrint("SHA-256", cert),
3142
                        sigName,
3143 3144
                        withWeak(pkey),
                        cert.getVersion()
D
duke 已提交
3145 3146 3147 3148 3149
                        };
        out.println(form.format(source));

        if (cert instanceof X509CertImpl) {
            X509CertImpl impl = (X509CertImpl)cert;
3150 3151 3152 3153 3154
            X509CertInfo certInfo = (X509CertInfo)impl.get(X509CertImpl.NAME
                                                           + "." +
                                                           X509CertImpl.INFO);
            CertificateExtensions exts = (CertificateExtensions)
                    certInfo.get(X509CertInfo.EXTENSIONS);
3155
            if (exts != null) {
3156
                printExtensions(rb.getString("Extensions."), exts, out);
3157
            }
3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171
        }
    }

    private static void printExtensions(String title, CertificateExtensions exts, PrintStream out)
            throws Exception {
        int extnum = 0;
        Iterator<Extension> i1 = exts.getAllExtensions().iterator();
        Iterator<Extension> i2 = exts.getUnparseableExtensions().values().iterator();
        while (i1.hasNext() || i2.hasNext()) {
            Extension ext = i1.hasNext()?i1.next():i2.next();
            if (extnum == 0) {
                out.println();
                out.println(title);
                out.println();
D
duke 已提交
3172
            }
3173 3174 3175 3176
            out.print("#"+(++extnum)+": "+ ext);
            if (ext.getClass() == Extension.class) {
                byte[] v = ext.getExtensionValue();
                if (v.length == 0) {
3177
                    out.println(rb.getString(".Empty.value."));
3178
                } else {
3179
                    new sun.misc.HexDumpEncoder().encodeBuffer(ext.getExtensionValue(), out);
3180
                    out.println();
D
duke 已提交
3181 3182
                }
            }
3183
            out.println();
D
duke 已提交
3184 3185 3186 3187
        }
    }

    /**
3188 3189 3190 3191 3192 3193
     * Locates a signer for a given certificate from a given keystore and
     * returns the signer's certificate.
     * @param cert the certificate whose signer is searched, not null
     * @param ks the keystore to search with, not null
     * @return <code>cert</code> itself if it's already inside <code>ks</code>,
     * or a certificate inside <code>ks</code> who signs <code>cert</code>,
3194
     * or null otherwise. A label is added.
D
duke 已提交
3195
     */
3196
    private static Pair<String,Certificate>
3197
            getSigner(Certificate cert, KeyStore ks) throws Exception {
3198
        if (ks.getCertificateAlias(cert) != null) {
3199
            return new Pair<>("", cert);
3200 3201 3202 3203 3204 3205 3206 3207
        }
        for (Enumeration<String> aliases = ks.aliases();
                aliases.hasMoreElements(); ) {
            String name = aliases.nextElement();
            Certificate trustedCert = ks.getCertificate(name);
            if (trustedCert != null) {
                try {
                    cert.verify(trustedCert.getPublicKey());
3208
                    return new Pair<>(name, trustedCert);
3209 3210 3211 3212
                } catch (Exception e) {
                    // Not verified, skip to the next one
                }
            }
D
duke 已提交
3213
        }
3214
        return null;
D
duke 已提交
3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235
    }

    /**
     * Gets an X.500 name suitable for inclusion in a certification request.
     */
    private X500Name getX500Name() throws IOException {
        BufferedReader in;
        in = new BufferedReader(new InputStreamReader(System.in));
        String commonName = "Unknown";
        String organizationalUnit = "Unknown";
        String organization = "Unknown";
        String city = "Unknown";
        String state = "Unknown";
        String country = "Unknown";
        X500Name name;
        String userInput = null;

        int maxRetry = 20;
        do {
            if (maxRetry-- < 0) {
                throw new RuntimeException(rb.getString(
3236
                        "Too.many.retries.program.terminated"));
D
duke 已提交
3237 3238
            }
            commonName = inputString(in,
3239
                    rb.getString("What.is.your.first.and.last.name."),
D
duke 已提交
3240 3241 3242
                    commonName);
            organizationalUnit = inputString(in,
                    rb.getString
3243
                        ("What.is.the.name.of.your.organizational.unit."),
D
duke 已提交
3244 3245
                    organizationalUnit);
            organization = inputString(in,
3246
                    rb.getString("What.is.the.name.of.your.organization."),
D
duke 已提交
3247 3248
                    organization);
            city = inputString(in,
3249
                    rb.getString("What.is.the.name.of.your.City.or.Locality."),
D
duke 已提交
3250 3251
                    city);
            state = inputString(in,
3252
                    rb.getString("What.is.the.name.of.your.State.or.Province."),
D
duke 已提交
3253 3254 3255
                    state);
            country = inputString(in,
                    rb.getString
3256
                        ("What.is.the.two.letter.country.code.for.this.unit."),
D
duke 已提交
3257 3258 3259 3260
                    country);
            name = new X500Name(commonName, organizationalUnit, organization,
                                city, state, country);
            MessageFormat form = new MessageFormat
3261
                (rb.getString("Is.name.correct."));
D
duke 已提交
3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277
            Object[] source = {name};
            userInput = inputString
                (in, form.format(source), rb.getString("no"));
        } while (collator.compare(userInput, rb.getString("yes")) != 0 &&
                 collator.compare(userInput, rb.getString("y")) != 0);

        System.err.println();
        return name;
    }

    private String inputString(BufferedReader in, String prompt,
                               String defaultValue)
        throws IOException
    {
        System.err.println(prompt);
        MessageFormat form = new MessageFormat
3278
                (rb.getString(".defaultValue."));
D
duke 已提交
3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
        Object[] source = {defaultValue};
        System.err.print(form.format(source));
        System.err.flush();

        String value = in.readLine();
        if (value == null || collator.compare(value, "") == 0) {
            value = defaultValue;
        }
        return value;
    }

    /**
     * Writes an X.509 certificate in base64 or binary encoding to an output
     * stream.
     */
    private void dumpCert(Certificate cert, PrintStream out)
        throws IOException, CertificateException
    {
        if (rfc) {
            out.println(X509Factory.BEGIN_CERT);
3299
            out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(cert.getEncoded()));
D
duke 已提交
3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339
            out.println(X509Factory.END_CERT);
        } else {
            out.write(cert.getEncoded()); // binary
        }
    }

    /**
     * Converts a byte to hex digit and writes to the supplied buffer
     */
    private void byte2hex(byte b, StringBuffer buf) {
        char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                            '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        int high = ((b & 0xf0) >> 4);
        int low = (b & 0x0f);
        buf.append(hexChars[high]);
        buf.append(hexChars[low]);
    }

    /**
     * Converts a byte array to hex string
     */
    private String toHexString(byte[] block) {
        StringBuffer buf = new StringBuffer();
        int len = block.length;
        for (int i = 0; i < len; i++) {
             byte2hex(block[i], buf);
             if (i < len-1) {
                 buf.append(":");
             }
        }
        return buf.toString();
    }

    /**
     * Recovers (private) key associated with given alias.
     *
     * @return an array of objects, where the 1st element in the array is the
     * recovered private key, and the 2nd element is the password used to
     * recover it.
     */
3340
    private Pair<Key,char[]> recoverKey(String alias, char[] storePass,
D
duke 已提交
3341 3342 3343 3344 3345
                                       char[] keyPass)
        throws Exception
    {
        Key key = null;

3346 3347 3348 3349 3350
        if (KeyStoreUtil.isWindowsKeyStore(storetype)) {
            key = keyStore.getKey(alias, null);
            return Pair.of(key, null);
        }

D
duke 已提交
3351 3352
        if (keyStore.containsAlias(alias) == false) {
            MessageFormat form = new MessageFormat
3353
                (rb.getString("Alias.alias.does.not.exist"));
D
duke 已提交
3354 3355 3356 3357 3358 3359
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }
        if (!keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class) &&
                !keyStore.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)) {
            MessageFormat form = new MessageFormat
3360
                (rb.getString("Alias.alias.has.no.key"));
D
duke 已提交
3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }

        if (keyPass == null) {
            // Try to recover the key using the keystore password
            try {
                key = keyStore.getKey(alias, storePass);

                keyPass = storePass;
                passwords.add(keyPass);
            } catch (UnrecoverableKeyException e) {
                // Did not work out, so prompt user for key password
                if (!token) {
                    keyPass = getKeyPasswd(alias, null, null);
                    key = keyStore.getKey(alias, keyPass);
                } else {
                    throw e;
                }
            }
        } else {
            key = keyStore.getKey(alias, keyPass);
        }

3385
        return Pair.of(key, keyPass);
D
duke 已提交
3386 3387 3388 3389 3390 3391 3392 3393 3394
    }

    /**
     * Recovers entry associated with given alias.
     *
     * @return an array of objects, where the 1st element in the array is the
     * recovered entry, and the 2nd element is the password used to
     * recover it (null if no password).
     */
3395
    private Pair<Entry,char[]> recoverEntry(KeyStore ks,
D
duke 已提交
3396 3397 3398 3399 3400 3401
                            String alias,
                            char[] pstore,
                            char[] pkey) throws Exception {

        if (ks.containsAlias(alias) == false) {
            MessageFormat form = new MessageFormat
3402
                (rb.getString("Alias.alias.does.not.exist"));
D
duke 已提交
3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }

        PasswordProtection pp = null;
        Entry entry;

        try {
            // First attempt to access entry without key password
            // (PKCS11 entry or trusted certificate entry, for example)

            entry = ks.getEntry(alias, pp);
            pkey = null;
        } catch (UnrecoverableEntryException une) {

            if(P11KEYSTORE.equalsIgnoreCase(ks.getType()) ||
                KeyStoreUtil.isWindowsKeyStore(ks.getType())) {
                // should not happen, but a possibility
                throw une;
            }

            // entry is protected

            if (pkey != null) {

                // try provided key password

                pp = new PasswordProtection(pkey);
                entry = ks.getEntry(alias, pp);

            } else {

                // try store pass

                try {
                    pp = new PasswordProtection(pstore);
                    entry = ks.getEntry(alias, pp);
                    pkey = pstore;
                } catch (UnrecoverableEntryException une2) {
                    if (P12KEYSTORE.equalsIgnoreCase(ks.getType())) {

                        // P12 keystore currently does not support separate
                        // store and entry passwords

                        throw une2;
                    } else {

                        // prompt for entry password

                        pkey = getKeyPasswd(alias, null, null);
                        pp = new PasswordProtection(pkey);
                        entry = ks.getEntry(alias, pp);
                    }
                }
            }
        }

3460
        return Pair.of(entry, pkey);
D
duke 已提交
3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476
    }
    /**
     * Gets the requested finger print of the certificate.
     */
    private String getCertFingerPrint(String mdAlg, Certificate cert)
        throws Exception
    {
        byte[] encCertInfo = cert.getEncoded();
        MessageDigest md = MessageDigest.getInstance(mdAlg);
        byte[] digest = md.digest(encCertInfo);
        return toHexString(digest);
    }

    /**
     * Prints warning about missing integrity check.
     */
3477
    private void printNoIntegrityWarning() {
D
duke 已提交
3478 3479
        System.err.println();
        System.err.println(rb.getString
3480
            (".WARNING.WARNING.WARNING."));
D
duke 已提交
3481
        System.err.println(rb.getString
3482
            (".The.integrity.of.the.information.stored.in.your.keystore."));
D
duke 已提交
3483
        System.err.println(rb.getString
3484
            (".WARNING.WARNING.WARNING."));
D
duke 已提交
3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501
        System.err.println();
    }

    /**
     * Validates chain in certification reply, and returns the ordered
     * elements of the chain (with user certificate first, and root
     * certificate last in the array).
     *
     * @param alias the alias name
     * @param userCert the user certificate of the alias
     * @param replyCerts the chain provided in the reply
     */
    private Certificate[] validateReply(String alias,
                                        Certificate userCert,
                                        Certificate[] replyCerts)
        throws Exception
    {
3502 3503 3504

        checkWeak(rb.getString("reply"), replyCerts);

D
duke 已提交
3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516
        // order the certs in the reply (bottom-up).
        // we know that all certs in the reply are of type X.509, because
        // we parsed them using an X.509 certificate factory
        int i;
        PublicKey userPubKey = userCert.getPublicKey();
        for (i=0; i<replyCerts.length; i++) {
            if (userPubKey.equals(replyCerts[i].getPublicKey())) {
                break;
            }
        }
        if (i == replyCerts.length) {
            MessageFormat form = new MessageFormat(rb.getString
3517
                ("Certificate.reply.does.not.contain.public.key.for.alias."));
D
duke 已提交
3518 3519 3520 3521 3522 3523 3524
            Object[] source = {alias};
            throw new Exception(form.format(source));
        }

        Certificate tmpCert = replyCerts[0];
        replyCerts[0] = replyCerts[i];
        replyCerts[i] = tmpCert;
3525 3526

        X509Certificate thisCert = (X509Certificate)replyCerts[0];
D
duke 已提交
3527 3528

        for (i=1; i < replyCerts.length-1; i++) {
3529
            // find a cert in the reply who signs thisCert
D
duke 已提交
3530 3531
            int j;
            for (j=i; j<replyCerts.length; j++) {
3532
                if (KeyStoreUtil.signedBy(thisCert, (X509Certificate)replyCerts[j])) {
D
duke 已提交
3533 3534 3535
                    tmpCert = replyCerts[i];
                    replyCerts[i] = replyCerts[j];
                    replyCerts[j] = tmpCert;
3536
                    thisCert = (X509Certificate)replyCerts[i];
D
duke 已提交
3537 3538 3539 3540 3541
                    break;
                }
            }
            if (j == replyCerts.length) {
                throw new Exception
3542
                    (rb.getString("Incomplete.certificate.chain.in.reply"));
D
duke 已提交
3543 3544 3545 3546 3547 3548 3549
            }
        }

        if (noprompt) {
            return replyCerts;
        }

3550
        // do we trust the cert at the top?
D
duke 已提交
3551
        Certificate topCert = replyCerts[replyCerts.length-1];
3552
        boolean fromKeyStore = true;
3553
        Pair<String,Certificate> root = getSigner(topCert, keyStore);
3554
        if (root == null && trustcacerts && caks != null) {
3555
            root = getSigner(topCert, caks);
3556
            fromKeyStore = false;
3557 3558 3559 3560
        }
        if (root == null) {
            System.err.println();
            System.err.println
3561
                    (rb.getString("Top.level.certificate.in.reply."));
3562 3563
            printX509Cert((X509Certificate)topCert, System.out);
            System.err.println();
3564
            System.err.print(rb.getString(".is.not.trusted."));
3565
            printWeakWarnings(true);
3566
            String reply = getYesNoReply
3567
                    (rb.getString("Install.reply.anyway.no."));
3568 3569
            if ("NO".equals(reply)) {
                return null;
D
duke 已提交
3570
            }
3571
        } else {
3572
            if (root.snd != topCert) {
3573 3574 3575 3576 3577
                // append the root CA cert to the chain
                Certificate[] tmpCerts =
                    new Certificate[replyCerts.length+1];
                System.arraycopy(replyCerts, 0, tmpCerts, 0,
                                 replyCerts.length);
3578
                tmpCerts[tmpCerts.length-1] = root.snd;
3579
                replyCerts = tmpCerts;
3580 3581 3582 3583 3584
                checkWeak(String.format(rb.getString(fromKeyStore ?
                                            "alias.in.keystore" :
                                            "alias.in.cacerts"),
                                        root.fst),
                          root.snd);
D
duke 已提交
3585 3586 3587 3588 3589 3590 3591
            }
        }
        return replyCerts;
    }

    /**
     * Establishes a certificate chain (using trusted certificates in the
3592
     * keystore and cacerts), starting with the reply (certToVerify)
D
duke 已提交
3593 3594
     * and ending at a self-signed certificate found in the keystore.
     *
3595 3596 3597 3598 3599 3600
     * @param userCert optional existing certificate, mostly likely be the
     *                 original self-signed cert created by -genkeypair.
     *                 It must have the same public key as certToVerify
     *                 but cannot be the same cert.
     * @param certToVerify the starting certificate to build the chain
     * @returns the established chain, might be null if user decides not
D
duke 已提交
3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612
     */
    private Certificate[] establishCertChain(Certificate userCert,
                                             Certificate certToVerify)
        throws Exception
    {
        if (userCert != null) {
            // Make sure that the public key of the certificate reply matches
            // the original public key in the keystore
            PublicKey origPubKey = userCert.getPublicKey();
            PublicKey replyPubKey = certToVerify.getPublicKey();
            if (!origPubKey.equals(replyPubKey)) {
                throw new Exception(rb.getString
3613
                        ("Public.keys.in.reply.and.keystore.don.t.match"));
D
duke 已提交
3614 3615 3616 3617 3618 3619
            }

            // If the two certs are identical, we're done: no need to import
            // anything
            if (certToVerify.equals(userCert)) {
                throw new Exception(rb.getString
3620
                        ("Certificate.reply.and.certificate.in.keystore.are.identical"));
D
duke 已提交
3621 3622 3623 3624 3625 3626 3627
            }
        }

        // Build a hash table of all certificates in the keystore.
        // Use the subject distinguished name as the key into the hash table.
        // All certificates associated with the same subject distinguished
        // name are stored in the same hash table entry as a vector.
3628
        Hashtable<Principal, Vector<Pair<String,X509Certificate>>> certs = null;
D
duke 已提交
3629
        if (keyStore.size() > 0) {
3630
            certs = new Hashtable<>(11);
D
duke 已提交
3631 3632 3633 3634 3635
            keystorecerts2Hashtable(keyStore, certs);
        }
        if (trustcacerts) {
            if (caks!=null && caks.size()>0) {
                if (certs == null) {
3636
                    certs = new Hashtable<>(11);
D
duke 已提交
3637 3638 3639 3640 3641 3642
                }
                keystorecerts2Hashtable(caks, certs);
            }
        }

        // start building chain
3643 3644 3645 3646 3647 3648 3649 3650 3651 3652
        Vector<Pair<String,X509Certificate>> chain = new Vector<>(2);
        if (buildChain(
                new Pair<>(rb.getString("the.input"),
                           (X509Certificate) certToVerify),
                chain, certs)) {
            for (Pair<String,X509Certificate> p : chain) {
                checkWeak(p.fst, p.snd);
            }
            Certificate[] newChain =
                    new Certificate[chain.size()];
D
duke 已提交
3653 3654 3655 3656 3657
            // buildChain() returns chain with self-signed root-cert first and
            // user-cert last, so we need to invert the chain before we store
            // it
            int j=0;
            for (int i=chain.size()-1; i>=0; i--) {
3658
                newChain[j] = chain.elementAt(i).snd;
D
duke 已提交
3659 3660 3661 3662 3663
                j++;
            }
            return newChain;
        } else {
            throw new Exception
3664
                (rb.getString("Failed.to.establish.chain.from.reply"));
D
duke 已提交
3665 3666 3667 3668
        }
    }

    /**
3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679
     * Recursively tries to establish chain from pool of certs starting from
     * certToVerify until a self-signed cert is found, and fill the certs found
     * into chain. Each cert in the chain signs the next one.
     *
     * This method is able to recover from an error, say, if certToVerify
     * is signed by certA but certA has no issuer in certs and itself is not
     * self-signed, the method can try another certB that also signs
     * certToVerify and look for signer of certB, etc, etc.
     *
     * Each cert in chain comes with a label showing its origin. The label is
     * used in the warning message when the cert is considered a risk.
D
duke 已提交
3680 3681 3682 3683 3684 3685 3686
     *
     * @param certToVerify the cert that needs to be verified.
     * @param chain the chain that's being built.
     * @param certs the pool of trusted certs
     *
     * @return true if successful, false otherwise.
     */
3687 3688 3689
    private boolean buildChain(Pair<String,X509Certificate> certToVerify,
            Vector<Pair<String,X509Certificate>> chain,
            Hashtable<Principal, Vector<Pair<String,X509Certificate>>> certs) {
3690
        if (KeyStoreUtil.isSelfSigned(certToVerify.snd)) {
D
duke 已提交
3691 3692 3693 3694 3695 3696
            // reached self-signed root cert;
            // no verification needed because it's trusted.
            chain.addElement(certToVerify);
            return true;
        }

3697 3698
        Principal issuer = certToVerify.snd.getIssuerDN();

D
duke 已提交
3699
        // Get the issuer's certificate(s)
3700
        Vector<Pair<String,X509Certificate>> vec = certs.get(issuer);
D
duke 已提交
3701 3702 3703 3704 3705 3706 3707
        if (vec == null) {
            return false;
        }

        // Try out each certificate in the vector, until we find one
        // whose public key verifies the signature of the certificate
        // in question.
3708
        for (Enumeration<Pair<String,X509Certificate>> issuerCerts = vec.elements();
D
duke 已提交
3709
             issuerCerts.hasMoreElements(); ) {
3710 3711
            Pair<String,X509Certificate> issuerCert = issuerCerts.nextElement();
            PublicKey issuerPubKey = issuerCert.snd.getPublicKey();
D
duke 已提交
3712
            try {
3713
                certToVerify.snd.verify(issuerPubKey);
D
duke 已提交
3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737
            } catch (Exception e) {
                continue;
            }
            if (buildChain(issuerCert, chain, certs)) {
                chain.addElement(certToVerify);
                return true;
            }
        }
        return false;
    }

    /**
     * Prompts user for yes/no decision.
     *
     * @return the user's decision, can only be "YES" or "NO"
     */
    private String getYesNoReply(String prompt)
        throws IOException
    {
        String reply = null;
        int maxRetry = 20;
        do {
            if (maxRetry-- < 0) {
                throw new RuntimeException(rb.getString(
3738
                        "Too.many.retries.program.terminated"));
D
duke 已提交
3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751
            }
            System.err.print(prompt);
            System.err.flush();
            reply = (new BufferedReader(new InputStreamReader
                                        (System.in))).readLine();
            if (collator.compare(reply, "") == 0 ||
                collator.compare(reply, rb.getString("n")) == 0 ||
                collator.compare(reply, rb.getString("no")) == 0) {
                reply = "NO";
            } else if (collator.compare(reply, rb.getString("y")) == 0 ||
                       collator.compare(reply, rb.getString("yes")) == 0) {
                reply = "YES";
            } else {
3752
                System.err.println(rb.getString("Wrong.answer.try.again"));
D
duke 已提交
3753 3754 3755 3756 3757 3758 3759 3760 3761
                reply = null;
            }
        } while (reply == null);
        return reply;
    }

    /**
     * Stores the (leaf) certificates of a keystore in a hashtable.
     * All certs belonging to the same CA are stored in a vector that
3762 3763
     * in turn is stored in the hashtable, keyed by the CA's subject DN.
     * Each cert comes with a string label that shows its origin and alias.
D
duke 已提交
3764 3765
     */
    private void keystorecerts2Hashtable(KeyStore ks,
3766
                Hashtable<Principal, Vector<Pair<String,X509Certificate>>> hash)
D
duke 已提交
3767 3768 3769 3770 3771 3772 3773 3774
        throws Exception {

        for (Enumeration<String> aliases = ks.aliases();
                                        aliases.hasMoreElements(); ) {
            String alias = aliases.nextElement();
            Certificate cert = ks.getCertificate(alias);
            if (cert != null) {
                Principal subjectDN = ((X509Certificate)cert).getSubjectDN();
3775 3776 3777 3778 3779 3780 3781 3782
                Pair<String,X509Certificate> pair = new Pair<>(
                        String.format(
                                rb.getString(ks == caks ?
                                        "alias.in.cacerts" :
                                        "alias.in.keystore"),
                                alias),
                        (X509Certificate)cert);
                Vector<Pair<String,X509Certificate>> vec = hash.get(subjectDN);
D
duke 已提交
3783
                if (vec == null) {
3784 3785
                    vec = new Vector<>();
                    vec.addElement(pair);
D
duke 已提交
3786
                } else {
3787 3788
                    if (!vec.contains(pair)) {
                        vec.addElement(pair);
D
duke 已提交
3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803
                    }
                }
                hash.put(subjectDN, vec);
            }
        }
    }

    /**
     * Returns the issue time that's specified the -startdate option
     * @param s the value of -startdate option
     */
    private static Date getStartDate(String s) throws IOException {
        Calendar c = new GregorianCalendar();
        if (s != null) {
            IOException ioe = new IOException(
3804
                    rb.getString("Illegal.startdate.value"));
D
duke 已提交
3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878
            int len = s.length();
            if (len == 0) {
                throw ioe;
            }
            if (s.charAt(0) == '-' || s.charAt(0) == '+') {
                // Form 1: ([+-]nnn[ymdHMS])+
                int start = 0;
                while (start < len) {
                    int sign = 0;
                    switch (s.charAt(start)) {
                        case '+': sign = 1; break;
                        case '-': sign = -1; break;
                        default: throw ioe;
                    }
                    int i = start+1;
                    for (; i<len; i++) {
                        char ch = s.charAt(i);
                        if (ch < '0' || ch > '9') break;
                    }
                    if (i == start+1) throw ioe;
                    int number = Integer.parseInt(s.substring(start+1, i));
                    if (i >= len) throw ioe;
                    int unit = 0;
                    switch (s.charAt(i)) {
                        case 'y': unit = Calendar.YEAR; break;
                        case 'm': unit = Calendar.MONTH; break;
                        case 'd': unit = Calendar.DATE; break;
                        case 'H': unit = Calendar.HOUR; break;
                        case 'M': unit = Calendar.MINUTE; break;
                        case 'S': unit = Calendar.SECOND; break;
                        default: throw ioe;
                    }
                    c.add(unit, sign * number);
                    start = i + 1;
                }
            } else  {
                // Form 2: [yyyy/mm/dd] [HH:MM:SS]
                String date = null, time = null;
                if (len == 19) {
                    date = s.substring(0, 10);
                    time = s.substring(11);
                    if (s.charAt(10) != ' ')
                        throw ioe;
                } else if (len == 10) {
                    date = s;
                } else if (len == 8) {
                    time = s;
                } else {
                    throw ioe;
                }
                if (date != null) {
                    if (date.matches("\\d\\d\\d\\d\\/\\d\\d\\/\\d\\d")) {
                        c.set(Integer.valueOf(date.substring(0, 4)),
                                Integer.valueOf(date.substring(5, 7))-1,
                                Integer.valueOf(date.substring(8, 10)));
                    } else {
                        throw ioe;
                    }
                }
                if (time != null) {
                    if (time.matches("\\d\\d:\\d\\d:\\d\\d")) {
                        c.set(Calendar.HOUR_OF_DAY, Integer.valueOf(time.substring(0, 2)));
                        c.set(Calendar.MINUTE, Integer.valueOf(time.substring(0, 2)));
                        c.set(Calendar.SECOND, Integer.valueOf(time.substring(0, 2)));
                        c.set(Calendar.MILLISECOND, 0);
                    } else {
                        throw ioe;
                    }
                }
            }
        }
        return c.getTime();
    }

3879 3880 3881
    /**
     * Match a command (may be abbreviated) with a command set.
     * @param s the command provided
3882 3883 3884
     * @param list the legal command set. If there is a null, commands after it
     * are regarded experimental, which means they are supported but their
     * existence should not be revealed to user.
3885 3886 3887 3888 3889 3890
     * @return the position of a single match, or -1 if none matched
     * @throws Exception if s is ambiguous
     */
    private static int oneOf(String s, String... list) throws Exception {
        int[] match = new int[list.length];
        int nmatch = 0;
3891
        int experiment = Integer.MAX_VALUE;
3892 3893
        for (int i = 0; i<list.length; i++) {
            String one = list[i];
3894 3895 3896 3897
            if (one == null) {
                experiment = i;
                continue;
            }
W
weijun 已提交
3898 3899
            if (one.toLowerCase(Locale.ENGLISH)
                    .startsWith(s.toLowerCase(Locale.ENGLISH))) {
3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918
                match[nmatch++] = i;
            } else {
                StringBuffer sb = new StringBuffer();
                boolean first = true;
                for (char c: one.toCharArray()) {
                    if (first) {
                        sb.append(c);
                        first = false;
                    } else {
                        if (!Character.isLowerCase(c)) {
                            sb.append(c);
                        }
                    }
                }
                if (sb.toString().equalsIgnoreCase(s)) {
                    match[nmatch++] = i;
                }
            }
        }
3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929
        if (nmatch == 0) {
            return -1;
        } else if (nmatch == 1) {
            return match[0];
        } else {
            // If multiple matches is in experimental commands, ignore them
            if (match[1] > experiment) {
                return match[0];
            }
            StringBuffer sb = new StringBuffer();
            MessageFormat form = new MessageFormat(rb.getString
3930
                ("command.{0}.is.ambiguous."));
3931 3932 3933 3934 3935 3936 3937 3938
            Object[] source = {s};
            sb.append(form.format(source));
            sb.append("\n    ");
            for (int i=0; i<nmatch && match[i]<experiment; i++) {
                sb.append(' ');
                sb.append(list[match[i]]);
            }
            throw new Exception(sb.toString());
3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953
        }
    }

    /**
     * Create a GeneralName object from known types
     * @param t one of 5 known types
     * @param v value
     * @return which one
     */
    private GeneralName createGeneralName(String t, String v)
            throws Exception {
        GeneralNameInterface gn;
        int p = oneOf(t, "EMAIL", "URI", "DNS", "IP", "OID");
        if (p < 0) {
            throw new Exception(rb.getString(
3954
                    "Unrecognized.GeneralName.type.") + t);
3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973
        }
        switch (p) {
            case 0: gn = new RFC822Name(v); break;
            case 1: gn = new URIName(v); break;
            case 2: gn = new DNSName(v); break;
            case 3: gn = new IPAddressName(v); break;
            default: gn = new OIDName(v); break; //4
        }
        return new GeneralName(gn);
    }

    private static final String[] extSupported = {
                        "BasicConstraints",
                        "KeyUsage",
                        "ExtendedKeyUsage",
                        "SubjectAlternativeName",
                        "IssuerAlternativeName",
                        "SubjectInfoAccess",
                        "AuthorityInfoAccess",
3974 3975
                        null,
                        "CRLDistributionPoints",
3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987
    };

    private ObjectIdentifier findOidForExtName(String type)
            throws Exception {
        switch (oneOf(type, extSupported)) {
            case 0: return PKIXExtensions.BasicConstraints_Id;
            case 1: return PKIXExtensions.KeyUsage_Id;
            case 2: return PKIXExtensions.ExtendedKeyUsage_Id;
            case 3: return PKIXExtensions.SubjectAlternativeName_Id;
            case 4: return PKIXExtensions.IssuerAlternativeName_Id;
            case 5: return PKIXExtensions.SubjectInfoAccess_Id;
            case 6: return PKIXExtensions.AuthInfoAccess_Id;
3988
            case 8: return PKIXExtensions.CRLDistributionPoints_Id;
3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021
            default: return new ObjectIdentifier(type);
        }
    }

    /**
     * Create X509v3 extensions from a string representation. Note that the
     * SubjectKeyIdentifierExtension will always be created non-critical besides
     * the extension requested in the <code>extstr</code> argument.
     *
     * @param reqex the requested extensions, can be null, used for -gencert
     * @param ext the original extensions, can be null, used for -selfcert
     * @param extstrs -ext values, Read keytool doc
     * @param pkey the public key for the certificate
     * @param akey the public key for the authority (issuer)
     * @return the created CertificateExtensions
     */
    private CertificateExtensions createV3Extensions(
            CertificateExtensions reqex,
            CertificateExtensions ext,
            List <String> extstrs,
            PublicKey pkey,
            PublicKey akey) throws Exception {

        if (ext != null && reqex != null) {
            // This should not happen
            throw new Exception("One of request and original should be null.");
        }
        if (ext == null) ext = new CertificateExtensions();
        try {
            // name{:critical}{=value}
            // Honoring requested extensions
            if (reqex != null) {
                for(String extstr: extstrs) {
W
weijun 已提交
4022
                    if (extstr.toLowerCase(Locale.ENGLISH).startsWith("honored=")) {
4023
                        List<String> list = Arrays.asList(
W
weijun 已提交
4024
                                extstr.toLowerCase(Locale.ENGLISH).substring(8).split(","));
4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048
                        // First check existence of "all"
                        if (list.contains("all")) {
                            ext = reqex;    // we know ext was null
                        }
                        // one by one for others
                        for (String item: list) {
                            if (item.equals("all")) continue;

                            // add or remove
                            boolean add = true;
                            // -1, unchanged, 0 crtical, 1 non-critical
                            int action = -1;
                            String type = null;
                            if (item.startsWith("-")) {
                                add = false;
                                type = item.substring(1);
                            } else {
                                int colonpos = item.indexOf(':');
                                if (colonpos >= 0) {
                                    type = item.substring(0, colonpos);
                                    action = oneOf(item.substring(colonpos+1),
                                            "critical", "non-critical");
                                    if (action == -1) {
                                        throw new Exception(rb.getString
4049
                                            ("Illegal.value.") + item);
4050 4051 4052 4053 4054
                                    }
                                }
                            }
                            String n = reqex.getNameByOid(findOidForExtName(type));
                            if (add) {
4055
                                Extension e = reqex.get(n);
4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086
                                if (!e.isCritical() && action == 0
                                        || e.isCritical() && action == 1) {
                                    e = Extension.newExtension(
                                            e.getExtensionId(),
                                            !e.isCritical(),
                                            e.getExtensionValue());
                                    ext.set(n, e);
                                }
                            } else {
                                ext.delete(n);
                            }
                        }
                        break;
                    }
                }
            }
            for(String extstr: extstrs) {
                String name, value;
                boolean isCritical = false;

                int eqpos = extstr.indexOf('=');
                if (eqpos >= 0) {
                    name = extstr.substring(0, eqpos);
                    value = extstr.substring(eqpos+1);
                } else {
                    name = extstr;
                    value = null;
                }

                int colonpos = name.indexOf(':');
                if (colonpos >= 0) {
4087
                    if (oneOf(name.substring(colonpos+1), "critical") == 0) {
4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112
                        isCritical = true;
                    }
                    name = name.substring(0, colonpos);
                }

                if (name.equalsIgnoreCase("honored")) {
                    continue;
                }
                int exttype = oneOf(name, extSupported);
                switch (exttype) {
                    case 0:     // BC
                        int pathLen = -1;
                        boolean isCA = false;
                        if (value == null) {
                            isCA = true;
                        } else {
                            try {   // the abbr format
                                pathLen = Integer.parseInt(value);
                                isCA = true;
                            } catch (NumberFormatException ufe) {
                                // ca:true,pathlen:1
                                for (String part: value.split(",")) {
                                    String[] nv = part.split(":");
                                    if (nv.length != 2) {
                                        throw new Exception(rb.getString
4113
                                                ("Illegal.value.") + extstr);
4114 4115 4116 4117 4118 4119 4120
                                    } else {
                                        if (nv[0].equalsIgnoreCase("ca")) {
                                            isCA = Boolean.parseBoolean(nv[1]);
                                        } else if (nv[0].equalsIgnoreCase("pathlen")) {
                                            pathLen = Integer.parseInt(nv[1]);
                                        } else {
                                            throw new Exception(rb.getString
4121
                                                ("Illegal.value.") + extstr);
4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147
                                        }
                                    }
                                }
                            }
                        }
                        ext.set(BasicConstraintsExtension.NAME,
                                new BasicConstraintsExtension(isCritical, isCA,
                                pathLen));
                        break;
                    case 1:     // KU
                        if(value != null) {
                            boolean[] ok = new boolean[9];
                            for (String s: value.split(",")) {
                                int p = oneOf(s,
                                       "digitalSignature",  // (0),
                                       "nonRepudiation",    // (1)
                                       "keyEncipherment",   // (2),
                                       "dataEncipherment",  // (3),
                                       "keyAgreement",      // (4),
                                       "keyCertSign",       // (5),
                                       "cRLSign",           // (6),
                                       "encipherOnly",      // (7),
                                       "decipherOnly",      // (8)
                                       "contentCommitment"  // also (1)
                                       );
                                if (p < 0) {
4148
                                    throw new Exception(rb.getString("Unknown.keyUsage.type.") + s);
4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161
                                }
                                if (p == 9) p = 1;
                                ok[p] = true;
                            }
                            KeyUsageExtension kue = new KeyUsageExtension(ok);
                            // The above KeyUsageExtension constructor does not
                            // allow isCritical value, so...
                            ext.set(KeyUsageExtension.NAME, Extension.newExtension(
                                    kue.getExtensionId(),
                                    isCritical,
                                    kue.getExtensionValue()));
                        } else {
                            throw new Exception(rb.getString
4162
                                    ("Illegal.value.") + extstr);
4163 4164 4165 4166
                        }
                        break;
                    case 2:     // EKU
                        if(value != null) {
4167
                            Vector<ObjectIdentifier> v = new Vector<>();
4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185
                            for (String s: value.split(",")) {
                                int p = oneOf(s,
                                        "anyExtendedKeyUsage",
                                        "serverAuth",       //1
                                        "clientAuth",       //2
                                        "codeSigning",      //3
                                        "emailProtection",  //4
                                        "",                 //5
                                        "",                 //6
                                        "",                 //7
                                        "timeStamping",     //8
                                        "OCSPSigning"       //9
                                       );
                                if (p < 0) {
                                    try {
                                        v.add(new ObjectIdentifier(s));
                                    } catch (Exception e) {
                                        throw new Exception(rb.getString(
4186
                                                "Unknown.extendedkeyUsage.type.") + s);
4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197
                                    }
                                } else if (p == 0) {
                                    v.add(new ObjectIdentifier("2.5.29.37.0"));
                                } else {
                                    v.add(new ObjectIdentifier("1.3.6.1.5.5.7.3." + p));
                                }
                            }
                            ext.set(ExtendedKeyUsageExtension.NAME,
                                    new ExtendedKeyUsageExtension(isCritical, v));
                        } else {
                            throw new Exception(rb.getString
4198
                                    ("Illegal.value.") + extstr);
4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225
                        }
                        break;
                    case 3:     // SAN
                    case 4:     // IAN
                        if(value != null) {
                            String[] ps = value.split(",");
                            GeneralNames gnames = new GeneralNames();
                            for(String item: ps) {
                                colonpos = item.indexOf(':');
                                if (colonpos < 0) {
                                    throw new Exception("Illegal item " + item + " in " + extstr);
                                }
                                String t = item.substring(0, colonpos);
                                String v = item.substring(colonpos+1);
                                gnames.add(createGeneralName(t, v));
                            }
                            if (exttype == 3) {
                                ext.set(SubjectAlternativeNameExtension.NAME,
                                        new SubjectAlternativeNameExtension(
                                            isCritical, gnames));
                            } else {
                                ext.set(IssuerAlternativeNameExtension.NAME,
                                        new IssuerAlternativeNameExtension(
                                            isCritical, gnames));
                            }
                        } else {
                            throw new Exception(rb.getString
4226
                                    ("Illegal.value.") + extstr);
4227 4228 4229 4230 4231 4232
                        }
                        break;
                    case 5:     // SIA, always non-critical
                    case 6:     // AIA, always non-critical
                        if (isCritical) {
                            throw new Exception(rb.getString(
4233
                                    "This.extension.cannot.be.marked.as.critical.") + extstr);
4234 4235 4236
                        }
                        if(value != null) {
                            List<AccessDescription> accessDescriptions =
4237
                                    new ArrayList<>();
4238 4239 4240 4241 4242 4243
                            String[] ps = value.split(",");
                            for(String item: ps) {
                                colonpos = item.indexOf(':');
                                int colonpos2 = item.indexOf(':', colonpos+1);
                                if (colonpos < 0 || colonpos2 < 0) {
                                    throw new Exception(rb.getString
4244
                                            ("Illegal.value.") + extstr);
4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262
                                }
                                String m = item.substring(0, colonpos);
                                String t = item.substring(colonpos+1, colonpos2);
                                String v = item.substring(colonpos2+1);
                                int p = oneOf(m,
                                        "",
                                        "ocsp",         //1
                                        "caIssuers",    //2
                                        "timeStamping", //3
                                        "",
                                        "caRepository"  //5
                                        );
                                ObjectIdentifier oid;
                                if (p < 0) {
                                    try {
                                        oid = new ObjectIdentifier(m);
                                    } catch (Exception e) {
                                        throw new Exception(rb.getString(
4263
                                                "Unknown.AccessDescription.type.") + m);
4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279
                                    }
                                } else {
                                    oid = new ObjectIdentifier("1.3.6.1.5.5.7.48." + p);
                                }
                                accessDescriptions.add(new AccessDescription(
                                        oid, createGeneralName(t, v)));
                            }
                            if (exttype == 5) {
                                ext.set(SubjectInfoAccessExtension.NAME,
                                        new SubjectInfoAccessExtension(accessDescriptions));
                            } else {
                                ext.set(AuthorityInfoAccessExtension.NAME,
                                        new AuthorityInfoAccessExtension(accessDescriptions));
                            }
                        } else {
                            throw new Exception(rb.getString
4280
                                    ("Illegal.value.") + extstr);
4281 4282
                        }
                        break;
4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301
                    case 8: // CRL, experimental, only support 1 distributionpoint
                        if(value != null) {
                            String[] ps = value.split(",");
                            GeneralNames gnames = new GeneralNames();
                            for(String item: ps) {
                                colonpos = item.indexOf(':');
                                if (colonpos < 0) {
                                    throw new Exception("Illegal item " + item + " in " + extstr);
                                }
                                String t = item.substring(0, colonpos);
                                String v = item.substring(colonpos+1);
                                gnames.add(createGeneralName(t, v));
                            }
                            ext.set(CRLDistributionPointsExtension.NAME,
                                    new CRLDistributionPointsExtension(
                                        isCritical, Collections.singletonList(
                                        new DistributionPoint(gnames, null, null))));
                        } else {
                            throw new Exception(rb.getString
4302
                                    ("Illegal.value.") + extstr);
4303 4304
                        }
                        break;
4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330
                    case -1:
                        ObjectIdentifier oid = new ObjectIdentifier(name);
                        byte[] data = null;
                        if (value != null) {
                            data = new byte[value.length() / 2 + 1];
                            int pos = 0;
                            for (char c: value.toCharArray()) {
                                int hex;
                                if (c >= '0' && c <= '9') {
                                    hex = c - '0' ;
                                } else if (c >= 'A' && c <= 'F') {
                                    hex = c - 'A' + 10;
                                } else if (c >= 'a' && c <= 'f') {
                                    hex = c - 'a' + 10;
                                } else {
                                    continue;
                                }
                                if (pos % 2 == 0) {
                                    data[pos/2] = (byte)(hex << 4);
                                } else {
                                    data[pos/2] += hex;
                                }
                                pos++;
                            }
                            if (pos % 2 != 0) {
                                throw new Exception(rb.getString(
4331
                                        "Odd.number.of.hex.digits.found.") + extstr);
4332 4333 4334 4335 4336 4337 4338 4339 4340
                            }
                            data = Arrays.copyOf(data, pos/2);
                        } else {
                            data = new byte[0];
                        }
                        ext.set(oid.toString(), new Extension(oid, isCritical,
                                new DerValue(DerValue.tag_OctetString, data)
                                        .toByteArray()));
                        break;
4341 4342
                    default:
                        throw new Exception(rb.getString(
4343
                                "Unknown.extension.type.") + extstr);
4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360
                }
            }
            // always non-critical
            ext.set(SubjectKeyIdentifierExtension.NAME,
                    new SubjectKeyIdentifierExtension(
                        new KeyIdentifier(pkey).getIdentifier()));
            if (akey != null && !pkey.equals(akey)) {
                ext.set(AuthorityKeyIdentifierExtension.NAME,
                        new AuthorityKeyIdentifierExtension(
                        new KeyIdentifier(akey), null, null));
            }
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
        return ext;
    }

4361 4362 4363 4364 4365 4366 4367 4368 4369
    private boolean isTrustedCert(Certificate cert) throws KeyStoreException {
        if (caks != null && caks.getCertificateAlias(cert) != null) {
            return true;
        } else {
            String inKS = keyStore.getCertificateAlias(cert);
            return inKS != null && keyStore.isCertificateEntry(inKS);
        }
    }

4370 4371
    private void checkWeak(String label, String sigAlg, Key key) {

4372 4373
        if (sigAlg != null && !DISABLED_CHECK.permits(
                SIG_PRIMITIVE_SET, sigAlg, null)) {
4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385
            weakWarnings.add(String.format(
                    rb.getString("whose.sigalg.risk"), label, sigAlg));
        }
        if (key != null && !DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) {
            weakWarnings.add(String.format(
                    rb.getString("whose.key.risk"),
                    label,
                    String.format(rb.getString("key.bit"),
                            KeyUtil.getKeySize(key), key.getAlgorithm())));
        }
    }

4386 4387
    private void checkWeak(String label, Certificate[] certs)
            throws KeyStoreException {
4388 4389 4390 4391 4392 4393 4394 4395
        for (int i = 0; i < certs.length; i++) {
            Certificate cert = certs[i];
            if (cert instanceof X509Certificate) {
                X509Certificate xc = (X509Certificate)cert;
                String fullLabel = label;
                if (certs.length > 1) {
                    fullLabel = oneInMany(label, i, certs.length);
                }
4396
                checkWeak(fullLabel, xc);
4397 4398 4399 4400
            }
        }
    }

4401 4402
    private void checkWeak(String label, Certificate cert)
            throws KeyStoreException {
4403 4404
        if (cert instanceof X509Certificate) {
            X509Certificate xc = (X509Certificate)cert;
4405 4406 4407
            // No need to check the sigalg of a trust anchor
            String sigAlg = isTrustedCert(cert) ? null : xc.getSigAlgName();
            checkWeak(label, sigAlg, xc.getPublicKey());
4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435
        }
    }

    private void checkWeak(String label, PKCS10 p10) {
        checkWeak(label, p10.getSigAlg(), p10.getSubjectPublicKeyInfo());
    }

    private void checkWeak(String label, CRL crl, Key key) {
        if (crl instanceof X509CRLImpl) {
            X509CRLImpl impl = (X509CRLImpl)crl;
            checkWeak(label, impl.getSigAlgName(), key);
        }
    }

    private void printWeakWarnings(boolean newLine) {
        if (!weakWarnings.isEmpty() && !nowarn) {
            System.err.println("\nWarning:");
            for (String warning : weakWarnings) {
                System.err.println(warning);
            }
            if (newLine) {
                // When calling before a yes/no prompt, add a new line
                System.err.println();
            }
        }
        weakWarnings.clear();
    }

D
duke 已提交
4436 4437 4438 4439
    /**
     * Prints the usage of this tool.
     */
    private void usage() {
W
weijun 已提交
4440 4441
        if (command != null) {
            System.err.println("keytool " + command +
4442
                    rb.getString(".OPTION."));
W
weijun 已提交
4443 4444 4445
            System.err.println();
            System.err.println(rb.getString(command.description));
            System.err.println();
4446
            System.err.println(rb.getString("Options."));
W
weijun 已提交
4447
            System.err.println();
4448

W
weijun 已提交
4449 4450 4451 4452 4453 4454 4455 4456 4457 4458
            // Left and right sides of the options list
            String[] left = new String[command.options.length];
            String[] right = new String[command.options.length];

            // Check if there's an unknown option
            boolean found = false;

            // Length of left side of options list
            int lenLeft = 0;
            for (int j=0; j<left.length; j++) {
4459 4460 4461 4462 4463
                Option opt = command.options[j];
                left[j] = opt.toString();
                if (opt.arg != null) left[j] += " " + opt.arg;
                if (left[j].length() > lenLeft) {
                    lenLeft = left[j].length();
W
weijun 已提交
4464
                }
4465
                right[j] = rb.getString(opt.description);
W
weijun 已提交
4466 4467 4468 4469 4470 4471 4472
            }
            for (int j=0; j<left.length; j++) {
                System.err.printf(" %-" + lenLeft + "s  %s\n",
                        left[j], right[j]);
            }
            System.err.println();
            System.err.println(rb.getString(
4473
                    "Use.keytool.help.for.all.available.commands"));
W
weijun 已提交
4474 4475
        } else {
            System.err.println(rb.getString(
4476
                    "Key.and.Certificate.Management.Tool"));
W
weijun 已提交
4477
            System.err.println();
4478
            System.err.println(rb.getString("Commands."));
W
weijun 已提交
4479 4480
            System.err.println();
            for (Command c: Command.values()) {
4481 4482
                if (c == KEYCLONE) break;
                System.err.printf(" %-20s%s\n", c, rb.getString(c.description));
W
weijun 已提交
4483 4484 4485
            }
            System.err.println();
            System.err.println(rb.getString(
4486
                    "Use.keytool.command.name.help.for.usage.of.command.name"));
W
weijun 已提交
4487
        }
D
duke 已提交
4488 4489 4490
    }

    private void tinyHelp() {
W
weijun 已提交
4491
        usage();
D
duke 已提交
4492 4493 4494 4495 4496 4497 4498 4499 4500 4501
        if (debug) {
            throw new RuntimeException("NO BIG ERROR, SORRY");
        } else {
            System.exit(1);
        }
    }

    private void errorNeedArgument(String flag) {
        Object[] source = {flag};
        System.err.println(new MessageFormat(
4502
                rb.getString("Command.option.flag.needs.an.argument.")).format(source));
D
duke 已提交
4503 4504
        tinyHelp();
    }
4505 4506

    private char[] getPass(String modifier, String arg) {
4507
        char[] output = KeyStoreUtil.getPassWithModifier(modifier, arg, rb);
4508 4509 4510 4511
        if (output != null) return output;
        tinyHelp();
        return null;    // Useless, tinyHelp() already exits.
    }
D
duke 已提交
4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532
}

// This class is exactly the same as com.sun.tools.javac.util.Pair,
// it's copied here since the original one is not included in JRE.
class Pair<A, B> {

    public final A fst;
    public final B snd;

    public Pair(A fst, B snd) {
        this.fst = fst;
        this.snd = snd;
    }

    public String toString() {
        return "Pair[" + fst + "," + snd + "]";
    }

    public boolean equals(Object other) {
        return
            other instanceof Pair &&
4533 4534
            Objects.equals(fst, ((Pair)other).fst) &&
            Objects.equals(snd, ((Pair)other).snd);
D
duke 已提交
4535 4536 4537 4538 4539 4540 4541
    }

    public int hashCode() {
        if (fst == null) return (snd == null) ? 0 : snd.hashCode() + 1;
        else if (snd == null) return fst.hashCode() + 2;
        else return fst.hashCode() * 17 + snd.hashCode();
    }
4542 4543

    public static <A,B> Pair<A,B> of(A a, B b) {
4544
        return new Pair<>(a,b);
4545
    }
D
duke 已提交
4546
}
4547