keystoremanager.java

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

JAVA
1,324
字号
            File file = filechooser.getSelectedFile();            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));            GeneralSecurityException e = null;            try {                CertificateFactory cf = CertificateFactory.getInstance("X.509");                while (in.available() > 0) {                    Certificate cert = cf.generateCertificate(in);                    if (keystore.getCertificateAlias(cert)==null) {                        if (alias==null) alias = file.getName();                        String talias = alias;                        int count = 0;                        while (keystore.containsAlias(talias)) {                            talias = alias + "-"+(++count);                        }                        keystore.setCertificateEntry(talias, cert);                        changed = true;                        if (list!=null) {                            ((DefaultListModel)list.getModel()).addElement(talias);                        }                    }                }            } catch (GeneralSecurityException e2) {                e = e2;            } finally {                in.close();            }            if (e!=null) {                try {                    KeyStore tempkeystore;                    String name = file.toString().toLowerCase();                    if (name.endsWith(".p12") || name.endsWith(".pkcs12") || name.endsWith(".pfx")) {                        tempkeystore = KeyStore.getInstance("pkcs12");                    } else {                        tempkeystore = KeyStore.getInstance("JKS");                    }                    in = new BufferedInputStream(new FileInputStream(file));                    tempkeystore.load(in, null);                    in.close();                    for (Enumeration i = tempkeystore.aliases();i.hasMoreElements();) {                        alias = (String)i.nextElement();                        Certificate cert;                        if (tempkeystore.isKeyEntry(alias)) {                            Certificate[] chain = tempkeystore.getCertificateChain(alias);                            cert = chain[chain.length-1];                        } else {                            cert = tempkeystore.getCertificate(alias);                        }                        if (keystore.getCertificateAlias(cert)==null) {                            String talias = alias;                            int count = 0;                            while (keystore.containsAlias(talias)) {                                talias = alias+"-"+(++count);                            }                            keystore.setCertificateEntry(talias, cert);                            changed = true;                            if (list!=null) {                                ((DefaultListModel)list.getModel()).addElement(talias);                            }                        }                    }                    e = null;                } catch (GeneralSecurityException e2) { }            }            if (e!=null) throw e;        }    }    /**     * Export a Certificate to a File     * @param alias the name of the entry to export     */    private void exportCertificate(String alias, String name) throws KeyStoreException, CertificateException, IOException {        JFileChooser filechooser = new JFileChooser((File)null);        if (name!=null) {            name = name.replaceAll("[.,\"';:/\\ ]", "")+".cer";            filechooser.setSelectedFile(new File(name));        }        if (keystore.isKeyEntry(alias)) {            setFileFilters(filechooser, new String[] { "cer", "pkcs12" }, "cer");        } else {            setFileFilters(filechooser, new String[] { "cer" }, "cer");        }        if (filechooser.showSaveDialog(parent)==JFileChooser.APPROVE_OPTION) {            File file = filechooser.getSelectedFile();            if (file.toString().toLowerCase().endsWith("p12") || file.toString().toLowerCase().endsWith("pkcs12") || file.toString().toLowerCase().endsWith("pfx")) {                JPasswordField password = new JPasswordField(10);                JPanel panel = new JPanel();                panel.add(new JLabel(SuperJOptionPane.getLocalizedString("Password")));                panel.add(password);                int action = JOptionPane.showConfirmDialog(null, panel, SuperJOptionPane.getLocalizedString("Password"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);                if (action == JOptionPane.OK_OPTION) {                    try {                        Key key = keystore.getKey(alias, password.getPassword());                        KeyStore store = KeyStore.getInstance("pkcs12");                        store.load(null);                        store.setKeyEntry(alias, key, password.getPassword(), keystore.getCertificateChain(alias));                        FileOutputStream out = new FileOutputStream(file);                        store.store(out, password.getPassword());                        out.close();                    } catch (GeneralSecurityException e) {                        JOptionPane.showMessageDialog(null, SuperJOptionPane.getLocalizedString("WrongPassword"));                                            }                }            }            FileOutputStream out = new FileOutputStream(file);            out.write("-----BEGIN X509 CERTIFICATE-----\n".getBytes("ISO-8859-1"));            out.flush();            Base64OutputStream bout = new Base64OutputStream(out);            bout.write(keystore.getCertificate(alias).getEncoded());            bout.flush();            out.write("\n-----END X509 CERTIFICATE-----\n".getBytes("ISO-8859-1"));            out.close();        }    }    /**     * Create a new Private Key entry     * @param list the list to add the component to     * @param alias the alias to use, or null to auto-generate one     * @return an arry of [ the alias the key is stored, password ] as or null if no key was generated     */    private Object[] createNewIdentity(JList list, String alias) throws GeneralSecurityException, IOException {        String[] countries = { "AF", "AL", "DZ", "AS", "AD", "AO", "AI", "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BR", "VG", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF", "TD", "CL", "CN", "CO", "KM", "CG", "CD", "CK", "CR", "CI", "HR", "CU", "CY", "CZ", "DK", "DJ", "DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FK", "FJ", "FI", "FR", "GF", "PF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GD", "GP", "GU", "GT", "GN", "GW", "GY", "HT", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IE", "IL", "IT", "JM", "JP", "JO", "KZ", "KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "AN", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", "PW", "PA", "PG", "PY", "PE", "PH", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", "WS", "SM", "ST", "SA", "SN", "RS", "SC", "SL", "SG", "SK", "SI", "SB", "SO", "ZA", "ES", "LK", "KN", "LC", "VC", "SD", "SR", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "VI", "UG", "UA", "AE", "GB", "US", "UY", "UZ", "VU", "VE", "VN", "YE", "ZM", "ZW" };        JComboBox countrycombo = new JComboBox(countries);        countrycombo.setRenderer(new DefaultListCellRenderer() {            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {                return super.getListCellRendererComponent(list, SuperJOptionPane.getLocalizedString("iso3166."+value), index, isSelected, cellHasFocus);            }        });        try {            countrycombo.setSelectedItem(Locale.getDefault().getCountry().toUpperCase());        } catch (Exception e) { }        LinkedHashMap map = new LinkedHashMap();        map.put("PleaseEnterDetails", null);        map.put("Name", new JTextField());        map.put("OrgUnit", new JTextField());        map.put("Organization", new JTextField());        map.put("City", new JTextField());        map.put("State", new JTextField());        map.put("Country", countrycombo);        map.put("Password", new JPasswordField());        map.put("ConfirmPassword", new JPasswordField());        Map values = new SuperJOptionPane(map) {            public String validate(Map values) {                if (!Arrays.equals((char[])values.get("Password"), (char[])values.get("ConfirmPassword"))) {                    return SuperJOptionPane.getLocalizedString("PasswordMismatch");                } else if (values.containsKey("Name") && ((String)values.get("Name")).indexOf(",")>=0) {                    return SuperJOptionPane.getLocalizedString("InvalidWhy", "No \",\" allowed in Name");                } else {                    return null;                }            }        }.getValues(parent, "CreateDigitalIdentity");        if (values!=null) {            String name = (String)values.get("Name");            String unit = (String)values.get("OrgUnitOptional");            String organization = (String)values.get("OrgOptional");            String city = (String)values.get("CityOptional");            String state = (String)values.get("StateOptional");            String country = (String)values.get("CountryOptional");            char[] password = (char[])values.get("Password");            alias = createSelfSignedKey(alias, name, unit, organization, city, state, country, password);            if (list!=null) {                ((DefaultListModel)list.getModel()).addElement(alias);            }            return new Object[] { alias, password };        } else {            return null;        }    }    /**     * Create a new 1024-bit RSA key with self-signed certificate, and add it     * to the supplied KeyStore     * @param alias the alias to store it as     * @param name the CN of the X.509 certificate     * @param unit the OU of the X.509 certificate     * @param organization the O of the X.509 certificate     * @param city the L of the X.509 certificate     * @param country the C of the X.509 certificate     * @param password the password to store the key with     * @throws GeneralSecurityException if something goes wrong     */    private String createSelfSignedKey(String alias, String name, String unit, String organization, String city, String state, String country, char[] password) throws GeneralSecurityException {        String dn = "";        if (name!=null) dn+="CN="+name+", ";        if (unit!=null) dn+="OU="+unit+", ";        if (organization!=null) dn+="O="+organization+", ";        if (city!=null) dn+="L="+city+", ";        if (country!=null) dn+="C="+country+", ";//        if (email!=null) dn+="EMAILADDRESS="+email+", ";        if (dn.length()==0) throw new IllegalArgumentException(SuperJOptionPane.getLocalizedString("OneNameRequired"));        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");        generator.initialize(1024, SecureRandom.getInstance("SHA1PRNG"));        KeyPair pair = generator.generateKeyPair();        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();        X500Principal subject = new X500Principal(dn.substring(0, dn.length()-2));        BigInteger serial = new BigInteger(64, new Random());        certGen.setSerialNumber(serial);        certGen.setIssuerDN(subject);        certGen.setNotBefore(new Date());        Date end = new Date(5000000000000l);     // 2012 sometime        certGen.setNotAfter(end);        certGen.setSubjectDN(subject);        certGen.setPublicKey(pair.getPublic());        certGen.setSignatureAlgorithm("SHA1withRSA");        X509Certificate cert = certGen.generate(pair.getPrivate());        if (alias==null) alias = serial.toString(16);        keystore.setKeyEntry(alias, pair.getPrivate(), password, new X509Certificate[] { cert });        changed = true;        return alias;    }    //-------------------------------------------------------------------------------------    private static class KeyCellRenderer implements ListCellRenderer {        private final KeyStore keystore;        private final Object[] certs;        public KeyCellRenderer(KeyStore keystore, Object[] certs) {            this.keystore = keystore;            this.certs = certs;        }        boolean isEnabled(String alias) {            boolean add = true;            if (certs!=null) {                for (int i=0;i<certs.length;i++) {                    try {                        X500Principal issuer = (X500Principal)Array.get(certs[i], 0);                        BigInteger serial = (BigInteger)Array.get(certs[i], 1);                        X509Certificate cert = (X509Certificate)keystore.getCertificate(alias);                        if (cert.getSerialNumber().equals(serial) && cert.getIssuerX500Principal().equals(issuer)) {                            return true;                        }                    } catch (Exception e2) { }                }                return false;            }            return true;        }        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean hasFocus) {            try {                String alias = (String)value;                isSelected &= isEnabled(alias);                X509Certificate cert = (X509Certificate)keystore.getCertificate(alias);                if (cert==null) {                    Certificate[] certs = keystore.getCertificateChain(alias);                    if (certs!=null) cert = (X509Certificate)certs[0];                }                String key = cert==null ? null : FormSignature.getSubjectField(cert, "CN");                if (key==null && cert!=null) key = FormSignature.getSubjectField(cert, "O");                if (key==null) key = alias;                JLabel label = new JLabel(key);                label.setEnabled(isEnabled(alias));                try {                    cert.checkValidity();                    label.setIcon(new ImageIcon(KeyStoreManager.class.getResource("resources/icons/accept.png")));                } catch (Exception e) {                    label.setIcon(new ImageIcon(KeyStoreManager.class.getResource("resources/icons/error.png")));                    label.setToolTipText(SuperJOptionPane.getLocalizedString("InvalidWhy", e.getMessage()));                }

⌨️ 快捷键说明

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