keystoremanager.java

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

JAVA
1,324
字号
        if (alias!=null) {            try {                final boolean iskey = keystore.isKeyEntry(alias);                DateFormat tdf = new SimpleDateFormat("dd MMM yyyy HH:mm");                DateFormat ddf = new SimpleDateFormat("dd MMM yyyy");                GridBagConstraints key = new GridBagConstraints();                GridBagConstraints val = new GridBagConstraints();                key.insets = new Insets(0, 0, 0, 10);                key.anchor = GridBagConstraints.PAGE_START;                key.fill = GridBagConstraints.HORIZONTAL;                key.gridx = GridBagConstraints.RELATIVE;                key.gridwidth = 1;                val.fill = GridBagConstraints.HORIZONTAL;                val.weightx = 1;                val.gridx = GridBagConstraints.RELATIVE;                val.gridwidth = GridBagConstraints.REMAINDER;                Certificate[] certs = keystore.getCertificateChain(alias);                if (certs==null) {                    certs = new Certificate[] { keystore.getCertificate(alias) };                }                final X509Certificate cert = (X509Certificate)certs[0];                if (cert==null) {                    throw new GeneralSecurityException("No Certificate for Alias \""+alias+"\"");                }                main.add(new JLabel("<html><b>"+SuperJOptionPane.getLocalizedString("Alias")+"</b></html>"), key);                main.add(new JLabel("<html><tt>"+alias+"<br><br></tt></html>"), val);                String name = null;                String field = FormSignature.getSubjectField(cert, "CN");                if (field!=null && field.length()>0) {                    main.add(new JLabel("<html><b>"+SuperJOptionPane.getLocalizedString("Name")+"</b></html>"), key);                    main.add(new JLabel(field), val);                    if (name==null) name = field;                }                field = FormSignature.getSubjectField(cert, "O");                if (field!=null && field.length()>0) {                    main.add(new JLabel("<html><b>"+SuperJOptionPane.getLocalizedString("Organization")+"</b></html>"), key);                    main.add(new JLabel(field), val);                    if (name==null) name = field;                }                field = FormSignature.getSubjectField(cert, "OU");                if (field!=null && field.length()>0) {                    main.add(new JLabel("<html><b>"+SuperJOptionPane.getLocalizedString("OrgUnit")+"</b></html>"), key);                    main.add(new JLabel(field), val);                    if (name==null) name = field;                }                field = FormSignature.getSubjectField(cert, "L");                if (field==null) field = "";                String state = FormSignature.getSubjectField(cert, "ST");                if (state!=null && state.length()>0) {                    if (field.length()>0) field+=", ";                    field += state;                }                state = FormSignature.getSubjectField(cert, "C");                if (state!=null && state.length()>0) {                    if (field.length()>0) field+=", ";                    field += state;                }                if (field.length()>0) {                    main.add(new JLabel("<html><b>"+SuperJOptionPane.getLocalizedString("Location")+"</b></html>"), key);                    main.add(new JLabel(field), val);                }                main.add(new JLabel("<html><b>"+SuperJOptionPane.getLocalizedString("Validity")+"</b></html>"), key);                field = Math.abs(cert.getNotBefore().getTime()-new Date().getTime()) > 1000*60*60*24*14 ? ddf.format(cert.getNotBefore()) : tdf.format(cert.getNotBefore());                field += "  -  ";                field += Math.abs(cert.getNotAfter().getTime()-new Date().getTime()) > 1000*60*60*24*14 ? ddf.format(cert.getNotAfter()) : tdf.format(cert.getNotAfter());                try {                    cert.checkValidity();                    main.add(new JLabel(field), val);                } catch (Exception e) {                    main.add(new JLabel("<html><font color='red'>"+SuperJOptionPane.getLocalizedString("Expired")+"</font>: "+field+"</html>"), val);                }                for (int i=0;i<certs.length;i++) {                    X509Certificate tempcert = (X509Certificate)certs[i];                    if (!tempcert.getIssuerDN().equals(tempcert.getSubjectDN())) {                        main.add(new JLabel("<html><b nowrap>"+SuperJOptionPane.getLocalizedString("IssuedBy")+"</b></html>"), key);                        field = "";                        String[] f = new String[] { "CN", "OU", "O", "L", "ST", "C" };                        for (int j=0;j<f.length;j++) {                            String bit = FormSignature.getIssuerField(tempcert, f[j]);                            if (bit!=null && bit.length()>0) {                                if (field.length()>0) field+=", ";                                field += bit;                            }                        }                        main.add(new JLabel("<html>"+field+"</html>"), val);                    }                }                JPanel buttons = new JPanel();                if (management) {                    final JButton delete = new JButton(SuperJOptionPane.getLocalizedString("Delete"));                    delete.setMnemonic(KeyEvent.VK_D);                    delete.addActionListener(new ActionListener() {                        public void actionPerformed(ActionEvent evt) {                            if (JOptionPane.showConfirmDialog(parent, SuperJOptionPane.getLocalizedString("ConfirmDeleteText"), SuperJOptionPane.getLocalizedString("Confirm"), JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION) {                                try {                                    keystore.deleteEntry(alias);                                    changed = true;                                    int index = list.getSelectedIndex();                                    ((DefaultListModel)list.getModel()).removeElementAt(index);                                    if (index==list.getModel().getSize()) index--;                                    if (index>=0) list.setSelectedIndex(index);                                } catch (Exception e) {                                    SuperJOptionPane.displayThrowable(SuperJOptionPane.getLocalizedString("Error"), e, parent);                                }                            }                        }                    });                    buttons.add(delete);                    final JButton export = new JButton(SuperJOptionPane.getLocalizedString("Export"));                    export.setMnemonic(KeyEvent.VK_E);                    final String fname = name;                    export.addActionListener(new ActionListener() {                        public void actionPerformed(ActionEvent evt) {                            try {                                exportCertificate((String)list.getSelectedValue(), fname);                            } catch (Exception e) {                                SuperJOptionPane.displayThrowable(SuperJOptionPane.getLocalizedString("Error"), e, parent);                            }                        }                    });                    buttons.add(export);                }                final JButton show = new JButton(SuperJOptionPane.getLocalizedString("ShowCertificate"));                show.setMnemonic(KeyEvent.VK_S);                show.addActionListener(new ActionListener() {                    public void actionPerformed(ActionEvent evt) {                        Window window = JOptionPane.getFrameForComponent(parent);                        final JDialog cdialog;                        if (window instanceof Frame) {                            cdialog = new JDialog((Frame)window, SuperJOptionPane.getLocalizedString("DigitalIdentities"), true);                        } else {                            cdialog = new JDialog((Dialog)window, SuperJOptionPane.getLocalizedString("DigitalIdentities"), true);                        }                        JTextArea field = new JTextArea();                        field.setFont(new Font("Monospace", 0, 9));                        field.setText(cert.toString());                        JScrollPane pane = new JScrollPane(field);                        pane.setPreferredSize(new Dimension(500, 300));                        JPanel buttons = new JPanel();                        final JButton ok = new JButton(SuperJOptionPane.getLocalizedString("OK"));                        ok.addActionListener(new ActionListener() {                            public void actionPerformed(ActionEvent evt) {                                cdialog.setVisible(false);                                cdialog.dispose();                            }                        });                        buttons.add(ok);                        JPanel body = new JPanel(new BorderLayout());                        body.add(pane, BorderLayout.CENTER);                        body.add(buttons, BorderLayout.SOUTH);                        cdialog.setContentPane(body);                        cdialog.setResizable(true);                        cdialog.pack();                        cdialog.setLocationRelativeTo(parent);                        cdialog.addWindowListener(new WindowAdapter() {                            public void windowClosing(WindowEvent evt) {                                cdialog.dispose();                            }                        });                        cdialog.setVisible(true);                    }                });                buttons.add(show);                val.gridx = 0;                val.weighty = 1;                val.anchor = GridBagConstraints.PAGE_END;                main.add(buttons, val);            } catch (GeneralSecurityException e) {                SuperJOptionPane.displayThrowable(SuperJOptionPane.getLocalizedString("Error"), e, parent);            }            main.setBorder(BorderFactory.createEtchedBorder());        } else {            main.setPreferredSize(new Dimension(400, 200));        }        return main;    }    /**     * Given a KeyStore, return a JList containing the aliases from that     * keystore that can be used as private keys.     * @param certs an optional list of Certificates that we're trying to match     * @since 2.8.3     */    private JList getEntryList(final KeyStore keystore, int type, Object[] certs) throws KeyStoreException {        TreeSet collection = new TreeSet(new Comparator() {            public int compare(Object o1, Object o2) {                try {                    if (o1==o2) return 0;                    X509Certificate c1 = (X509Certificate)keystore.getCertificate((String)o1);                    if (c1==null) c1 = (X509Certificate)(keystore.getCertificateChain((String)o1)[0]);                    X509Certificate c2 = (X509Certificate)keystore.getCertificate((String)o2);                    if (c2==null) c2 = (X509Certificate)(keystore.getCertificateChain((String)o2)[0]);                    String n1 = c1.getSubjectX500Principal().toString();                    String n2 = c2.getSubjectX500Principal().toString();                    int diff = n1.compareTo(n2);                    if (diff==0) diff = c1.getNotAfter().compareTo(c2.getNotAfter());                    if (diff==0) diff = c1.getSerialNumber().compareTo(c2.getSerialNumber());                    return diff;                } catch (GeneralSecurityException e) {                    return o1.hashCode() - o2.hashCode();                }            }        });        for (Enumeration e=keystore.aliases();e.hasMoreElements();) {            String talias = (String)e.nextElement();            if (type==0 && keystore.isKeyEntry(talias)) {                collection.add(talias);            } else if (type>0 && !keystore.isKeyEntry(talias)) {                X509Certificate cert = (X509Certificate)keystore.getCertificate(talias);                if ((cert.getVersion()==3 && cert.getBasicConstraints()==-1) == (type==1)) {                    collection.add(talias);                }            }        }        DefaultListModel model = new DefaultListModel();        for (Iterator i = collection.iterator();i.hasNext();) {            model.addElement(i.next());        }        JList list = new JList(model);        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);        list.setCellRenderer(new KeyCellRenderer(keystore, certs));        list.setVisibleRowCount(8);        return list;    }    //-----------------------------------------------------------------------------    // Management functions    private void importKey(JList list) throws GeneralSecurityException, IOException {        FileKeyStoreManager manager = new FileKeyStoreManager(parent, null, keystore.getProvider().getName());        KeyStore tempstore = manager.loadKeyStore();        if (tempstore!=null) {            Map map = showPrivateKeySelectionDialog(new KeyStore[] { tempstore }, null, null, null, null, null, null, false, false);            if (map!=null) {                String alias = (String)map.get("Alias");                String talias = alias;                char[] password = (char[])map.get("Password");                int count = 0;                while (keystore.containsAlias(talias)) {                    talias = alias+"-"+(++count);                }                keystore.setKeyEntry(talias, tempstore.getKey(alias, password), password, tempstore.getCertificateChain(alias));                changed = true;                if (list!=null) {                    ((DefaultListModel)list.getModel()).addElement(talias);                }            }        }    }    /**     * Import a Certificate from a File into the KeyStore and JList     * @param list the list to add the new alias to     * @param alias the alias to store the certificate against, or null to pick one     */    private void importCertificate(JList list, String alias) throws GeneralSecurityException, IOException {        JFileChooser filechooser = new JFileChooser((File)null);        setFileFilters(filechooser, new String[] { "cer", "keystore" }, "cer");        if (filechooser.showOpenDialog(parent)==JFileChooser.APPROVE_OPTION) {

⌨️ 快捷键说明

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