⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 keystoregui.java

📁 JAVA开源LDAP浏览器jxplorer的源码!
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
        {
            return;  // no cert selected
        }
        
        String alias = null;
        
        if (info.fileName != null)
        {
            alias = new File(info.fileName).getName();
            if (alias != null && alias.indexOf('.')>0)
                alias = alias.substring(0, alias.indexOf('.')); // trim to get the stem
        }
        
        if (alias == null)
            alias = CBIntText.get("default");
        
        boolean nameAlreadyExists = false;    
        do
        {            
            alias = (String)JOptionPane.showInputDialog(this, CBIntText.get("Please enter a short unique name for this Certificate"),
                CBIntText.get("Enter Certificate Alias"), JOptionPane.QUESTION_MESSAGE, null, null, alias);

            nameAlreadyExists = listContains(alias);
            if (nameAlreadyExists)
            {
                JOptionPane.showMessageDialog(this, CBIntText.get("That name already exists."),
                CBIntText.get("Duplicate Alias"), JOptionPane.ERROR_MESSAGE);
            }
        }    
        while (nameAlreadyExists);
                
        if (alias == null || alias.length() == 0)
            return; // nothing to do
            
        if (checkPassword() == false)
            return; // nothing to do.
            
        try
        {
            keystore.setCertificateEntry(alias, info.cert);

            refreshView();
            changed = true;
            return;            
        }
        catch (KeyStoreException e)
        {
            CBUtility.error(CBIntText.get("Error - unable to add key: {0} from key store", new String[] {alias}), e);
        }
        // FAILURE!
        try
        {
            keystore.deleteEntry(alias);  // try to clean up.
        }
        catch (Exception e)
        {}
    }
    
    /**
     *    Reread the key store after an addition or deletion operation,
     *    and refresh certListModel.
     */
    
    protected void refreshView()
    {
        CertItem[] certs = getKeyStoreCerts(keystore);
        
        if (certListModel == null)
            setupCertificateListGUI();
            
        certListModel.removeAllElements();
        for (int i=0; i<certs.length; i++)
            certListModel.addElement(certs[i]);
    }
    
    /**
     *    Initialise empty list models, and associate the 
     *    certificate list renderer with the cert list.
     *
     */
    
    protected void setupCertificateListGUI()
    {
        certListModel = new DefaultListModel();
        
        certList.setModel(certListModel);
        
        certList.setCellRenderer(new CertificateListRenderer());
    }
    
    /**
     *    Initialises a selection list of CertItems from the keystore.
     */
    
    protected void setupCertificateList()
    {
        // Initially read the keystore without a password, for
        // simple listing...
        
        keystore = readKeyStore(password, keystoreType, keystoreFile);
        
        setupCertificateListGUI();
        
        if (keystore == null)
            JOptionPane.showMessageDialog(this, CBIntText.get("Unable to find/open keystore: {0}", new String[] {keystoreFile}), CBIntText.get("Error: no Keystore"), JOptionPane.ERROR_MESSAGE);
        else
            refreshView();
    }
    
    
    /**
     *    The keystore has a particular password protecting its contents.
     *    This menu allows the user to change that password.
     */
    
    public class PasswordDialog extends CBDialog
    {
        public JPasswordField old, new1, new2;
        
        public PasswordDialog(Frame owner)
        {
            super(owner, CBIntText.get("Change the Key Store Password."), null);
            addln(new JLabel(getImageIcon("sslpassword.gif")));
            addln(new JLabel(CBIntText.get("This screen allows you to enter")));
            addln(new JLabel(CBIntText.get("a new key store password")));
            addln(new JLabel(" "));
            addln(new JLabel(CBIntText.get("Enter the old password")));
            addln(old = new JPasswordField());
            addln(new JLabel(CBIntText.get("The new Password") + ":"));
            addln(new1 = new JPasswordField());
            addln(new JLabel(CBIntText.get("Confirm the new Password") + ":"));
            addln(new2 = new JPasswordField());
            setSize(240, 320);
            CBUtility.center(this, owner);
        }
        
    }
    
    /**
     *   This allows the user to change the password used to protect
     *   the keystore.
     *
     */
    
    protected void setupPasswords()
    {
        PasswordDialog newPassword = new PasswordDialog(owner);
        
        
        // Various things can go wrong here - keep showing the
        // user the password change window until they enter a
        // valid set of passwords, or get sick of it...
        
        while (newPassword.wasCancelled() == false)
        {
            newPassword.setVisible(true);
            
            if (newPassword.wasCancelled())
                return; // do nothing.
                
            char[] oldPass, newPass1, newPass2;
            oldPass = newPassword.old.getPassword();
            newPass1 = newPassword.new1.getPassword();
            newPass2 = newPassword.new2.getPassword();
            
            if (Arrays.equals(newPass1, newPass2) == true)
            {
                // this throws an error directly to the user if it fails
                KeyStore newKeystore = readKeyStore(oldPass, keystoreType, keystoreFile);
                if (newKeystore != null)
                {
                    if (writeKeyStore(newPass1, newKeystore, keystoreFile, keystoreType) == true)
                    {
                        keystore = newKeystore;
                        password = newPass1;
                        
                        JOptionPane.showMessageDialog(this, CBIntText.get("Passwords successfully changed!"),
                                                      CBIntText.get("Success!"), JOptionPane.INFORMATION_MESSAGE);
                        return; // SUCCESS!
                    }
                }
                else
                    CBUtility.error(CBIntText.get("Unable to change password - incorrect password entered?"));
                    
            }
            else
            {
                CBUtility.error(CBIntText.get("The new passwords were not identical!"), null);
            }
        }
        
    }
    
    protected void clearPassword(char[] c)
    {
        if (c != null)
            for (int i=0; i<c.length; i++)
                c[i] = 0;
    }
    
    /**
     *    This extracts an array of CertItem-s from a keystore,
     *    for display in the GUI.
     *    @param keystore the keystore to use.
     *    @return an array of CertItem-s representing the certificates and aliases 
     *            stored in the keystore.
     */
    
    public static CertItem[] getKeyStoreCerts(KeyStore keystore)
    {
        try
        {
            Vector certVector = new Vector(10);  // vector of cert items...
            
            //PrivateKey privKey=null;
            
            Enumeration a = keystore.aliases();
            while ( a.hasMoreElements() )
            {
                String alias = (String) a.nextElement();
                CertItem item = new CertItem(alias);
                
                if ( keystore.isKeyEntry(alias) )
                {
                    X509Certificate userCert = (X509Certificate)keystore.getCertificate(alias);
                    item.addX509Cert(userCert);
                    item.setHasPrivateKey(true);
                }
                else
                {
                    X509Certificate userCert = (X509Certificate)keystore.getCertificate(alias);
                    item.addX509Cert(userCert);
                }
                certVector.add(item);
            }
            
            return (CertItem[]) certVector.toArray(new CertItem[0]);
        }
        catch (Exception e)
        {
            CBUtility.error(CBIntText.get("Error reading certificate from keystore."), e);
            return null;
        }
        
        
    }
    
    /**
     * initialises the keystore by reading the saved keystore file.
     * @param pass the password protecting the keystore.  If this is
     *        null, the keystore will be read-only, and no validation
     *        will be performed.
     * @param storeType - the type of the keystore.  Unless a custom
     *        security provider is being used, this will almost certainly
     *        be 'jks'.
     * @param keyFile the file name of the keystore.
     * @return the new keystore, or null if an error occurred.
     */
    
    public static KeyStore readKeyStore(char[] pass, String storeType, String keyFile)
    {
        //byte[] b=null;
        
        try
        {
            KeyStore keystore = KeyStore.getInstance( storeType );  // storeType is usually 'jks' for default java keystore
            
            FileInputStream fis = new FileInputStream(keyFile);
            keystore.load(fis, pass);
            
            fis.close();
            
            return keystore;
        }
        catch (Exception e)
        {
        
            CBUtility.error(CBIntText.get("Error opening certificate keystore {0}.  Probably an incorrect password", new String[] {keyFile}), e);
                            
            return null;
        }
    }
    
    /**
     *    writes the keystore to a password protected file.
     *    @param password the password to use while saving it.
     *    @param keystore the certificate key store to save.
     *    @param keyFile the name of the file to save to.
     *    @param keystoreType the type of store - e.g. "JKS" or "KSE" or "PKCS12"
     *    @return the success status of the operation.
     */
    
    public static boolean writeKeyStore(char[] password, KeyStore keystore, String keyFile, String keystoreType)
    {
        if ("KSE".equalsIgnoreCase(keystoreType))
        {
            CertItem[] certs = getKeyStoreCerts(keystore);
            
            if (certs.length > 2)
               return givePKCS12ErrorMsg(CBIntText.get("This PKCS12 File can only have one certificate, one key, and one CA certificate"));        
            
            if (certs.length == 2 && certs[0].hasPrivateKey && certs[1].hasPrivateKey)        
               return givePKCS12ErrorMsg(CBIntText.get("This PKCS12 File can only have one certificate, one key, and one CA certificate"));        
               
            // XXXcheck for if second cert if server certificate?               
        }
        FileOutputStream fos = null;
        try
        {
            if (password == null)
                throw new KeyStoreException("null password not allowed");
            fos = new FileOutputStream(keyFile);
            keystore.store(fos, password);
            fos.close();
            return true;
        }
        catch (Exception e)  // IOException or KeyStoreException
        {
            CBUtility.error(CBIntText.get("Error saving certificate keystore.") +
                            "\n" + CBIntText.get("Probably an invalid password"), e);

            // try to clean up any mess.
            if (fos != null)
                try {fos.close();} catch(IOException e2) {}

            return false;
        }

    }
    
    /**
     *    Utility to reduce code duplication above
     */
     
    private static boolean givePKCS12ErrorMsg(String msg)
    {
        CBUtility.error(msg);
        return false;
    }
    
    
    /**
     *    A representation of a certificate that is displayed
     *    in the certificate list.
     */
    

⌨️ 快捷键说明

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