4217 lines · 166.7 KB · Java
RawDownload
            throw new Exception(rb.getString                    ("Cannot.derive.signature.algorithm"));        }    }    /**     * 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)) {                keysize = 256;            } else if ("RSA".equalsIgnoreCase(keyAlgName)) {                keysize = 2048;            } else {                keysize = 1024;            }        }         if (alias == null) {            alias = keyAlias;        }         if (keyStore.containsAlias(alias)) {            MessageFormat form = new MessageFormat(rb.getString                ("Key.pair.not.generated.alias.alias.already.exists"));            Object[] source = {alias};            throw new Exception(form.format(source));        }         if (sigAlgName == null) {            sigAlgName = getCompatibleSigAlgName(keyAlgName);        }        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();         X509Certificate[] chain = new X509Certificate[1];        chain[0] = keypair.getSelfCertificate(                x500Name, getStartDate(startDate), validity*24L*60L*60L);         if (verbose) {            MessageFormat form = new MessageFormat(rb.getString                ("Generating.keysize.bit.keyAlgName.key.pair.and.self.signed.certificate.sigAlgName.with.a.validity.of.validality.days.for"));            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);        }        keyStore.setKeyEntry(alias, privKey, keyPass, chain);         // resign so that -ext are applied.        doSelfCert(alias, null, sigAlgName);    }     /**     * 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                (rb.getString("Destination.alias.dest.already.exists"));            Object[] source = {dest};            throw new Exception(form.format(source));        }         Pair<Entry,char[]> objs = recoverEntry(keyStore, orig, storePass, keyPass);        Entry entry = objs.fst;        keyPass = objs.snd;         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;        }        Pair<Key,char[]> objs = recoverKey(alias, storePass, keyPass);        Key privKey = objs.fst;        if (keyPass == null) {            keyPass = objs.snd;        }         if (keyPassNew == null) {            MessageFormat form = new MessageFormat                (rb.getString("key.password.for.alias."));            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    {        System.err.println(rb.getString            ("No.entries.from.identity.database.added"));    }     /**     * Prints a single keystore entry.     */    private void doPrintEntry(String alias, PrintStream out,                              boolean printWarning)        throws Exception    {        if (storePass == null && printWarning                && !KeyStoreUtil.isWindowsKeyStore(storetype)) {            printWarning();        }         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));        }         if (verbose || rfc || debug) {            MessageFormat form = new MessageFormat                (rb.getString("Alias.name.alias"));            Object[] source = {alias};            out.println(form.format(source));             if (!token) {                form = new MessageFormat(rb.getString                    ("Creation.date.keyStore.getCreationDate.alias."));                Object[] src = {keyStore.getCreationDate(alias)};                out.println(form.format(src));            }        } else {            if (!token) {                MessageFormat form = new MessageFormat                    (rb.getString("alias.keyStore.getCreationDate.alias."));                Object[] source = {alias, keyStore.getCreationDate(alias)};                out.print(form.format(source));            } else {                MessageFormat form = new MessageFormat                    (rb.getString("alias."));                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(                        rb.getString("Entry.type.type.")).format(source));            } else {                out.println("SecretKeyEntry, ");            }        } else if (keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {            if (verbose || rfc || debug) {                Object[] source = {"PrivateKeyEntry"};                out.println(new MessageFormat(                        rb.getString("Entry.type.type.")).format(source));            } else {                out.println("PrivateKeyEntry, ");            }             // Get the chain            Certificate[] chain = keyStore.getCertificateChain(alias);            if (chain != null) {                if (verbose || rfc || debug) {                    out.println(rb.getString                        ("Certificate.chain.length.") + chain.length);                    for (int i = 0; i < chain.length; i ++) {                        MessageFormat form = new MessageFormat                                (rb.getString("Certificate.i.1."));                        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);                        }                    }                } else {                    // Print the digest of the user cert only                    out.println                        (rb.getString("Certificate.fingerprint.SHA1.") +                        getCertFingerPrint("SHA1", chain[0]));                }            }        } else if (keyStore.entryInstanceOf(alias,                KeyStore.TrustedCertificateEntry.class)) {            // We have a trusted certificate entry            Certificate cert = keyStore.getCertificate(alias);            Object[] source = {"trustedCertEntry"};            String mf = new MessageFormat(                    rb.getString("Entry.type.type.")).format(source) + "\n";            if (verbose && (cert instanceof X509Certificate)) {                out.println(mf);                printX509Cert((X509Certificate)cert, out);            } else if (rfc) {                out.println(mf);                dumpCert(cert, out);            } else if (debug) {                out.println(cert.toString());            } else {                out.println("trustedCertEntry, ");                out.println(rb.getString("Certificate.fingerprint.SHA1.")                            + getCertFingerPrint("SHA1", cert));            }        } else {            out.println(rb.getString("Unknown.Entry.Type"));        }    }     /**     * Load the srckeystore from a stream, used in -importkeystore     * @returns the src KeyStore     */    KeyStore loadSourceKeyStore() throws Exception {        boolean isPkcs11 = false;         InputStream is = null;         if (P11KEYSTORE.equalsIgnoreCase(srcstoretype) ||                KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {            if (!NONE.equals(srcksfname)) {                System.err.println(MessageFormat.format(rb.getString                    (".keystore.must.be.NONE.if.storetype.is.{0}"), srcstoretype));                System.err.println();                tinyHelp();            }            isPkcs11 = true;        } else {            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);                }                is = new FileInputStream(srcksfile);            } else {                throw new Exception(rb.getString                        ("Please.specify.srckeystore"));            }        }         KeyStore store;        try {            if (srcProviderName == null) {                store = KeyStore.getInstance(srcstoretype);            } else {                store = KeyStore.getInstance(srcstoretype, srcProviderName);            }             if (srcstorePass == null                    && !srcprotectedPath                    && !KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {                System.err.print(rb.getString("Enter.source.keystore.password."));                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(                        "Warning.Different.store.and.key.passwords.not.supported.for.PKCS12.KeyStores.Ignoring.user.specified.command.value."));                    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)) {            // anti refactoring, copied from printWarning(),            // but change 2 lines            System.err.println();            System.err.println(rb.getString                (".WARNING.WARNING.WARNING."));            System.err.println(rb.getString                (".The.integrity.of.the.information.stored.in.the.srckeystore."));            System.err.println(rb.getString                (".WARNING.WARNING.WARNING."));            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     */    private void doImportKeyStore() throws Exception {         if (alias != null) {            doImportKeyStoreSingle(loadSourceKeyStore(), alias);        } else {            if (dest != null || srckeyPass != null || destKeyPass != null) {                throw new Exception(rb.getString(                        "if.alias.not.specified.destalias.srckeypass.and.destkeypass.must.not.be.specified"));            }            doImportKeyStoreAll(loadSourceKeyStore());        }        /*         * 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(                        "Warning.Overwriting.existing.alias.alias.in.destination.keystore")).format(source));            } else {                String reply = getYesNoReply(new MessageFormat(rb.getString(                        "Existing.entry.alias.alias.exists.overwrite.no.")).format(source));                if ("NO".equals(reply)) {                    newAlias = inputStringFromStdin(rb.getString                            ("Enter.new.alias.name.RETURN.to.cancel.import.for.this.entry."));                    if ("".equals(newAlias)) {                        System.err.println(new MessageFormat(rb.getString(                                "Entry.for.alias.alias.not.imported.")).format(                                source));                        return 0;                    }                }            }        }         Pair<Entry,char[]> objs = recoverEntry(srckeystore, alias, srcstorePass, srckeyPass);        Entry entry = objs.fst;         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.        if (destKeyPass != null) {            pp = new PasswordProtection(destKeyPass);        } else if (objs.snd != null) {            pp = new PasswordProtection(objs.snd);        }         try {            keyStore.setEntry(newAlias, entry, pp);            return 1;        } catch (KeyStoreException kse) {            Object[] source2 = {alias, kse.toString()};            MessageFormat form = new MessageFormat(rb.getString(                    "Problem.importing.entry.for.alias.alias.exception.Entry.for.alias.alias.not.imported."));            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};                MessageFormat form = new MessageFormat(rb.getString("Entry.for.alias.alias.successfully.imported."));                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(                "Import.command.completed.ok.entries.successfully.imported.fail.entries.failed.or.cancelled"));        System.err.println(form.format(source));    }     /**     * Prints all keystore entries.     */    private void doPrintEntries(PrintStream out)        throws Exception    {        if (storePass == null                && !KeyStoreUtil.isWindowsKeyStore(storetype)) {            printWarning();        } else {            out.println();        }         out.println(rb.getString("Keystore.type.") + keyStore.getType());        out.println(rb.getString("Keystore.provider.") +                keyStore.getProvider().getName());        out.println();         MessageFormat form;        form = (keyStore.size() == 1) ?                new MessageFormat(rb.getString                        ("Your.keystore.contains.keyStore.size.entry")) :                new MessageFormat(rb.getString                        ("Your.keystore.contains.keyStore.size.entries"));        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();            doPrintEntry(alias, out, false);            if (verbose || rfc) {                out.println(rb.getString("NEWLINE"));                out.println(rb.getString                        ("STAR"));                out.println(rb.getString                        ("STARNN"));            }

Lines 1501–2000 of 4217. Previous lines