keystoremanager.java

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

JAVA
1,324
字号
    /**     * Select and return a private key for signing     * @param alias the alias to preselect, if appropriate     * @param password the password to use on the alias     * @param extra Additional information for the dialog. Currently, the only acceptable value is a {@link Map} containing "Name", "Reason" and "Location" keys mapping to Strings.     * @return a Map containing an "Alias" and "Password" value or null if no matching alias is available or the dialog was cancelled.     */    public Map showSigningKeySelectionDialog(String alias, char[] password, Object extra) {        KeyStore keystore;        if ((keystore=getKeyStore())!=null) {            String name=null, reason=null, location=null;            if (extra!=null && extra instanceof Map) {                name = (String)((Map)extra).get("Name");                reason = (String)((Map)extra).get("Reason");                location = (String)((Map)extra).get("Location");            }            return showPrivateKeySelectionDialog(new KeyStore[] { keystore }, alias, password, name, reason, location, null, true, isKeyStoreReloadable());        } else {            return null;        }    }    /**     * Add the specified Certificate to the list of trusted root certificates     * and save the KeyStore.     * @param alias the alias to store it under - may be null     * @param cert the X509 Certificate to store     */    public void trustCertificate(String alias, X509Certificate cert) {        try {            if (getKeyStore()!=null) {                if (keystore.getCertificateAlias(cert)==null) {                    if (alias==null) alias = cert.getSerialNumber().toString(16);                    String talias = alias;                    int count = 0;                    while (keystore.containsAlias(talias)) {                        talias = alias+"-"+(++count);                    }                    keystore.setCertificateEntry(alias, cert);                    saveKeyStore(keystore);                }            }        } catch (Exception e) {            SuperJOptionPane.displayThrowable(SuperJOptionPane.getLocalizedString("Error"), e, parent);        }    }    //-----------------------------------------------------------------------    private Map showPrivateKeySelectionDialog(final KeyStore[] keystore, final String alias, char[] password, String name, String reason, String location, final Object[] matching, boolean signing, boolean reload) {        try {            final JDialog dialog;            final Map map = new HashMap();            Window window = JOptionPane.getFrameForComponent(parent);            if (window instanceof Frame) {                dialog = new JDialog((Frame)window, SuperJOptionPane.getLocalizedString("ManageIdentities"), true);            } else {                dialog = new JDialog((Dialog)window, SuperJOptionPane.getLocalizedString("ManageIdentities"), true);            }            final JPanel content = new JPanel(new GridBagLayout());            final GridBagConstraints call = new GridBagConstraints();            GridBagConstraints cbut = new GridBagConstraints();            GridBagConstraints ckey = new GridBagConstraints();            GridBagConstraints cval = new GridBagConstraints();            cbut.fill = ckey.fill = cval.fill = GridBagConstraints.HORIZONTAL;            call.fill = GridBagConstraints.BOTH;            call.weighty = call.weightx = 1;            cbut.gridwidth = call.gridwidth = cval.gridwidth = GridBagConstraints.REMAINDER;            if (password==null) password = getDefaultKeyPassword();            final JList[] list = new JList[] { getEntryList(keystore[0], 0, matching) };            if (alias!=null) list[0].setSelectedValue(alias, true);            if (list[0].getSelectedIndex()==-1 && list[0].getModel().getSize()>0) {                list[0].setSelectedIndex(0);            }            content.add(new JScrollPane(list[0]), call, 0);            final JPasswordField passwordfield = password!=null ? new JPasswordField(new String(password)) : new JPasswordField();            final JTextField namefield = name!=null ? new JTextField(name) : new JTextField();            final JTextField reasonfield = reason!=null ? new JTextField(reason) : new JTextField();            final JTextField locationfield = location!=null ? new JTextField(location) : new JTextField();            content.add(new JLabel(SuperJOptionPane.getLocalizedString("Password")), ckey);            content.add(passwordfield, cval);            if (signing) {                content.add(new JLabel(SuperJOptionPane.getLocalizedString("Name")), ckey);                content.add(namefield, cval);                content.add(new JLabel(SuperJOptionPane.getLocalizedString("Reason")), ckey);                content.add(reasonfield, cval);                content.add(new JLabel(SuperJOptionPane.getLocalizedString("Location")), ckey);                content.add(locationfield, cval);            }            // Buttons            final JPanel buttonpane = new JPanel();            if (reload) {                final JButton reloadbutton = new JButton(SuperJOptionPane.getLocalizedString("ReloadFile"));                reloadbutton.addActionListener(new ActionListener() {                    public void actionPerformed(ActionEvent evt) {                        try {                            keystore[0] = KeyStoreManager.this.keystore = reloadKeyStore();                            list[0] = getEntryList(keystore[0], 0, matching);                            if (alias!=null) list[0].setSelectedValue(alias, true);                            if (list[0].getSelectedIndex()==-1 && list[0].getModel().getSize()>0) {                                list[0].setSelectedIndex(0);                            }                            content.remove(0);                            content.add(new JScrollPane(list[0]), call, 0);                            content.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) {                    dialog.setVisible(false);                    dialog.dispose();                }            });            buttonpane.add(cancelbutton);            JButton okbutton = new JButton(SuperJOptionPane.getLocalizedString("OK"));            okbutton.addActionListener(new ActionListener() {                public void actionPerformed(ActionEvent evt) {                    String alias = (String)list[0].getSelectedValue();                    char[] password = passwordfield.getPassword();                    try {                        if (keystore[0].getKey(alias, password)!=null) {                            map.put("Alias", alias);                            map.put("Password", password);                            map.put("Name", namefield.getText());                            map.put("Reason", reasonfield.getText());                            map.put("Location", locationfield.getText());                        }                        dialog.dispose();                    } catch (Exception e) {                        JOptionPane.showMessageDialog(parent, SuperJOptionPane.getLocalizedString("WrongPassword"), SuperJOptionPane.getLocalizedString("Error"), JOptionPane.ERROR_MESSAGE);                     }                }            });            buttonpane.add(okbutton);            content.add(buttonpane, cbut);            content.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));            dialog.setContentPane(content);            dialog.setResizable(true);            dialog.pack();            dialog.setLocationRelativeTo(parent);            dialog.addWindowListener(new WindowAdapter() {                public void windowClosing(WindowEvent evt) {                    dialog.dispose();                }            });            if (signing && !hasPrivateKey(keystore[0])) {                Object[] x = createNewIdentity(list[0], null);                if (x!=null) {                    list[0].setSelectedIndex(0);                    passwordfield.setText(new String((char[])x[1]));                }            }            if (hasPrivateKey(keystore[0])) {                dialog.setVisible(true);            }            return map.isEmpty() ? null : map;        } catch (Exception e) {            SuperJOptionPane.displayThrowable(SuperJOptionPane.getLocalizedString("Error"), e, parent);        }        return null;    }    //------------------------------------------------------------------------------    // Panel creation    /**     * Return a JPanel containing the Identity Management functions     */    private JComponent getIdentityManagementPanel() throws KeyStoreException {        final JTabbedPane tabbedpane = new JTabbedPane();        tabbedpane.setTabPlacement(JTabbedPane.TOP);        tabbedpane.addTab(SuperJOptionPane.getLocalizedString("Keys"), null, getEntrySelectionPanel(0, true, true));        tabbedpane.addTab(SuperJOptionPane.getLocalizedString("Contacts"), null, getEntrySelectionPanel(1, true, true));        tabbedpane.addTab(SuperJOptionPane.getLocalizedString("Authorities"), null, getEntrySelectionPanel(2, true, true));        return tabbedpane;    }    /**     * Return a JPanel containing the widgets to select a Private Key or Certificate     * from the KeyStore     * @param key 0 to select Private Keys, 1 to select Certificates, 2 to select CA Roots     * @param newentry whether to allow the "Create Key" or "Import" button     * @param management whether to allow management functions on keys, eg delete     */    private JComponent getEntrySelectionPanel(final int type, boolean newentry, final boolean management) throws KeyStoreException {        final JSplitPane pane = new JSplitPane();        final JPanel left = new JPanel(new BorderLayout());        pane.setTopComponent(left);        final JList list = getEntryList(keystore, type, null);        list.addListSelectionListener(new ListSelectionListener() {            public void valueChanged(ListSelectionEvent e) {                pane.setBottomComponent(getEntryPanel(list, management));            }        });        JScrollPane scrollpane = new JScrollPane(list);        scrollpane.setMaximumSize(new Dimension(280,200));        scrollpane.setMinimumSize(new Dimension(280,200));        left.add(scrollpane, BorderLayout.CENTER);        if (newentry) {            JPanel leftbuttons = new JPanel();            if (type==0) {                JButton button = new JButton(SuperJOptionPane.getLocalizedString("New"));                button.setMnemonic(KeyEvent.VK_N);                button.addActionListener(new ActionListener() {                    public void actionPerformed(ActionEvent evt) {                        try {                            createNewIdentity(list, null);                        } catch (Exception e) {                            SuperJOptionPane.displayThrowable(SuperJOptionPane.getLocalizedString("Error"), e, parent);                        }                    }                });                leftbuttons.add(button);                button = new JButton(SuperJOptionPane.getLocalizedString("Import"));                button.setMnemonic(KeyEvent.VK_I);                button.addActionListener(new ActionListener() {                    public void actionPerformed(ActionEvent evt) {                        try {                            importKey(list);                        } catch (Exception e) {                            SuperJOptionPane.displayThrowable(SuperJOptionPane.getLocalizedString("Error"), e, parent);                        }                    }                });                leftbuttons.add(button);            } else {                JButton button = new JButton(SuperJOptionPane.getLocalizedString("Import"));                button.setMnemonic(KeyEvent.VK_I);                button.addActionListener(new ActionListener() {                    public void actionPerformed(ActionEvent evt) {                        try {                            importCertificate(list, null);                        } catch (Exception e) {                            SuperJOptionPane.displayThrowable(SuperJOptionPane.getLocalizedString("Error"), e, parent);                        }                    }                });                leftbuttons.add(button);            }            left.add(leftbuttons, BorderLayout.SOUTH);        }        pane.setBottomComponent(getEntryPanel(list, management));        return pane;    }    /**      * Create and return a Panel containin information on a single KeyStore entry     * @param list the List, the selected item of which is the alias we want to display     * @param management whether to allow the management functions, eg delete/export     */    private JPanel getEntryPanel(final JList list, boolean management) {        final String alias = list.getSelectedIndex()==-1 ? null : (String)list.getSelectedValue();        JPanel main = new JPanel(new GridBagLayout());

⌨️ 快捷键说明

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