keystoremanager.java

来自「Java生成PDF Java生成PDF Java生成PDF」· Java 代码 · 共 1,324 行 · 第 1/5 页

JAVA
1,324
字号
// $Id: KeyStoreManager.java,v 1.14 2007/11/16 04:12:00 mike Exp $package org.faceless.pdf2.viewer2;import org.bouncycastle2.x509.*;import org.faceless.util.Base64OutputStream;import java.math.BigInteger;import java.security.*;import java.text.*;import java.lang.reflect.Array;import java.security.cert.*;import java.security.cert.Certificate;import javax.security.auth.x500.*;import javax.swing.*;import javax.swing.event.*;import java.awt.*;import java.awt.event.*;import org.faceless.pdf2.FormSignature;import javax.swing.filechooser.FileFilter;import java.security.cert.*;import java.util.*;import java.io.*;/** * This class deals with managing digital identities in a KeyStore. It's * primary focus is to enable the following activities * <ul> * <li>Selection of a Private Key to open a PDF encrypted with a Public Key</li> * <li>Selection of a Private Key to digitally sign a PDF</li> * <li>Addition of a Certificate to the list of trusted root certificates</li> * <li>The ability to examine, create, import, export and delete certificates and keys</li> * </ul> * This class is abstract - subclasses need to implement the * {@link #loadKeyStore}, {@link #saveKeyStore} and friends methods. * * @since 2.8.3 */// Use Cases// * Open PublicKey PDF - Select Identity/Reload KeyStore//   * Load/Reload Keystore//   * Select key/password for decryption// * Sign PDF - Create Identity/Select Identity/Reload KeyStore//   * Load/Reload KeyStore//   * Select key/password for signing, prompt for reason/location/name too// * Trust Certificate - add a certificate from a signature//   * No dialog required// * Manage Identities//   * Load/Reload KeyStore//   * Create a new Key/Certificate//   * Import a Key/Certificate from another KeyStore//   * Import a Certificate from a certificate file or another KeyStore//   * Examine a Key or Certificate//   * Export a Certificate//   * Delete a Key or Certificate//// To Do//   * Select certificate for public key encryption - once we add PK enc.//// Warning - do not make any assumptions about the internals of this file,// they are liable to changepublic abstract class KeyStoreManager{    protected KeyStore keystore;    private boolean changed;    protected final Component parent;    private String name;    /**     * Create a new KeyStoreManager     * @param parent the Component to use as a parent for any dialogs - may be null     */    protected KeyStoreManager(Component parent) {        if (parent==null) parent = JOptionPane.getRootFrame();        this.parent = parent;    }    /**     * Get the KeyStore. May cause the KeyStore to be loaded or initialized     */    public final KeyStore getKeyStore() {        try {            if (keystore==null) keystore = loadKeyStore();        } catch (Exception e) {            SuperJOptionPane.displayThrowable("Error", e, parent);        }        return keystore;    }    /**     * Load or initialise a KeyStore     */    protected abstract KeyStore loadKeyStore() throws GeneralSecurityException, IOException;    /**     * Return true if the user should have an option to reload the KeyStore     */    protected abstract boolean isKeyStoreReloadable();    /**     * Reload the keystore     */    protected KeyStore reloadKeyStore() throws GeneralSecurityException, IOException {        return keystore;    }    /**     * Initialize the keystore. Creates a new keystore and add the root certificates     * from the default Java keystore     */    protected void initializeKeyStore(KeyStore keystore) throws GeneralSecurityException {        try {            keystore.load(null);            KeyStore defaults = KeyStore.getInstance("JKS");            defaults.load(getClass().getResourceAsStream("resources/defaultkeystore.jks"), null);            for (Enumeration e = defaults.aliases();e.hasMoreElements();) {                String alias = (String)e.nextElement();                keystore.setCertificateEntry(alias, defaults.getCertificate(alias));            }        } catch (Exception e) {            e.printStackTrace();        }        // This copies the certificates from FormSignature.loadDefaultKeyStore()        //        // KeyStore defkeystore = FormSignature.loadDefaultKeyStore();        // for (Enumeration e = defkeystore.aliases();e.hasMoreElements();) {        //     String alias = (String)e.nextElement();        //     if (defkeystore.isCertificateEntry(alias)) {        //         keystore.setCertificateEntry(alias, defkeystore.getCertificate(alias));        //     }        // }    }    /**     * Save the KeyStore     * @param keystore the KeyStore     * @return true if the KeyStore was saved or an unrecoverable error occurred, false otherwise     */    protected abstract boolean saveKeyStore(KeyStore keystore) throws GeneralSecurityException, IOException;    /**     * Return the default password to try when decrypting private keys.     * This is typically null, but may be the password set when the KeyStore was loaded.     */    protected char[] getDefaultKeyPassword() {        return null;    }    private static boolean hasPrivateKey(KeyStore keystore) {        try {            for (Enumeration e = keystore.aliases();e.hasMoreElements();) {                String alias = (String)e.nextElement();                if (keystore.isKeyEntry(alias)) return true;            }        } catch (Exception e) {}        return false;    }    /**     * Show the "Identity Management" dialog, which allows keys and certificats     * to be created/imported, viewed, exported or deleted.     */    public void showIdentityManagementDialog() {        try {            if (getKeyStore()!=null) {                final ByteArrayOutputStream backup = new ByteArrayOutputStream();                try {                    keystore.store(backup, new char[0]);                } catch (Exception e) { }                Window window = JOptionPane.getFrameForComponent(parent);                final JDialog dialog;                if (window instanceof Frame) {                    dialog = new JDialog((Frame)window, SuperJOptionPane.getLocalizedString("DigitalIdentities"), true);                } else {                    dialog = new JDialog((Dialog)window, SuperJOptionPane.getLocalizedString("DigitalIdentities"), true);                }                final JPanel body = new JPanel(new BorderLayout()) ;                body.add(getIdentityManagementPanel(), BorderLayout.CENTER, 0);                // Buttons                final JPanel buttonpane = new JPanel();                if (isKeyStoreReloadable()) {                    final JButton reloadbutton = new JButton(SuperJOptionPane.getLocalizedString("ReloadFile"));                    reloadbutton.addActionListener(new ActionListener() {                        public void actionPerformed(ActionEvent evt) {                            try {                                keystore = reloadKeyStore();                                backup.reset();                                try {                                    keystore.store(backup, new char[0]);                                } catch (Exception e) { }                                body.remove(0);                                body.add(getIdentityManagementPanel(), BorderLayout.CENTER, 0);                                body.validate();                            } catch (Exception e) {                                SuperJOptionPane.displayThrowable(SuperJOptionPane.getLocalizedString("Error"), e, parent);                            }                        }                    });                    buttonpane.add(reloadbutton);                }                JButton cancelbutton = new JButton(SuperJOptionPane.getLocalizedString("Cancel"));                cancelbutton.addActionListener(new ActionListener() {                    public void actionPerformed(ActionEvent evt) {                        try {                            keystore.load(new ByteArrayInputStream(backup.toByteArray()), new char[0]);                        } catch (Exception e) {}                        dialog.setVisible(false);                        dialog.dispose();                    }                });                buttonpane.add(cancelbutton);                JButton okbutton = new JButton(SuperJOptionPane.getLocalizedString("Save"));                okbutton.addActionListener(new ActionListener() {                    public void actionPerformed(ActionEvent evt) {                        try {                            if (!changed || saveKeyStore(keystore)) {                                dialog.dispose();                            }                        } catch (Exception e) {                            SuperJOptionPane.displayThrowable(SuperJOptionPane.getLocalizedString("Error"), e, parent);                        }                    }                });                buttonpane.add(okbutton);                body.add(buttonpane, BorderLayout.SOUTH);                dialog.setContentPane(body);                dialog.setResizable(true);                dialog.pack();                dialog.setLocationRelativeTo(parent);                dialog.addWindowListener(new WindowAdapter() {                    public void windowClosing(WindowEvent evt) {                        dialog.dispose();                    }                });                dialog.setVisible(true);            }        } catch (Exception e) {            SuperJOptionPane.displayThrowable(SuperJOptionPane.getLocalizedString("Error"), e, parent);        }    }    /**     * Select and return a private key for decryption     * @param alias the alias to preselect, if appropriate     * @param password the password to use on the alias     * @param extra additional information for the dialog     * @return a Map containing an "Alias" and "Password" value or null if no matching alias is available or the dialog was cancelled.     */    public Map showDecryptionKeySelectionDialog(String alias, char[] password, Object extra) {        KeyStore keystore;        if ((keystore=getKeyStore())!=null) {            Object[] matching = null;            try {                matching = (Object[])extra;            } catch (Exception e) {}            return showPrivateKeySelectionDialog(new KeyStore[] { keystore }, alias, password, null, null, null, matching, false, isKeyStoreReloadable());        } else {            return null;        }    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?