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

📄 keystoremanager.java

📁 这是linux下ssl vpn的实现程序
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
            log.error("Could not get certificate with alias " + alias + ".", e);
        }
        return null;
    }

    /**
     * Return an enumeration of {@link String} objects aliases or
     * <code>null</code> if the key store is not loaded.
     * 
     * @return enumeration of {@link Certificate} objects.
     */
    public Enumeration getCertificateAliases() {
        checkKeyStore();
        try {
            if (keyStore != null) {
                return keyStore.aliases();
            }
        } catch (Exception e) {
            log.error("Could not get certificates.", e);
        }
        return null;
    }

    /**
     * Get the number of keys / certificates in this key store
     * 
     * @return number of keys / certificates in this key store
     */
    public int getSize() {
        checkKeyStore();
        try {
            return keyStore != null ? keyStore.size() : 0;
        } catch (KeyStoreException e) {
            log.error("Failed to determine size of key store.", e);
        }
        return 0;
    }

    /**
     * Change the password used to encrypt this key store.
     * 
     * @param oldPassword old password
     * @param password new password
     * @throws Exception on any error
     */
    public void changeKeystorePassword(String oldPassword, String password) throws Exception {
        checkKeyStore();
        if (!isKeyStoreExists()) {
            throw new Exception("Key store doesn't exists. Password cannot be changed.");
        }
        CommandRunner runner = null;
        try {
            Vector v = new Vector();
            v.add(KEY_TOOL);
            v.add("-storepasswd");
            v.add("-new");
            v.add(password);
            v.add("-keystore");
            v.add(getKeyStoreFile().getAbsolutePath());
            v.add("-storepass");
            v.add(oldPassword);
            runner = new CommandRunner(v);
            runner.runCommand();
            this.storePassword = password;
        } catch (Exception e) {
            log.error("Failed to change keystore password.", e);
            throw new Exception(runner == null ? e.getMessage() : parseKeytoolOutput(runner.getOutput()));
        }

    }

    /**
     * Get a key pair from this key store
     * 
     * @param alias alias under which the pair is stored
     * @param password password protecting the keys if any
     * @return key pair
     */
    public KeyPair getKeyPair(String alias, char[] password) {
        try {
            checkKeyStore();
            if (isKeyStoreExists() && !isKeyStoreEmpty()) {
                Key key = keyStore.getKey(alias, password);
                if (key instanceof PrivateKey) {
                    Certificate cert = keyStore.getCertificate(alias);
                    PublicKey publicKey = cert.getPublicKey();
                    return new KeyPair(publicKey, (PrivateKey) key);
                }
            }
        } catch (Exception e) {
            log.error("Could not get key pair with alias " + alias + ".", e);
        }
        return null;
    }

    /**
     * Get a private key from this key store
     * 
     * @param alias alias under which the key is stored
     * @param password password protecting the key if any
     * @return key
     */
    public PrivateKey getPrivateKey(String alias, char[] password) {
        try {
            checkKeyStore();
            if (isKeyStoreExists() && !isKeyStoreEmpty()) {
                return (PrivateKey) keyStore.getKey(alias, password);
            }
        } catch (Exception e) {
            log.error("Could not get private key with alias " + alias + ".", e);
        }
        return null;
    }

    /**
     * Get the chain of certificates from the specified alias up to the root CA
     * certificate
     * 
     * @param alias alias
     * @return certificate chain
     */

    public Certificate[] getCertificateChain(String alias) {
        Certificate[] chain = null;
        try {
            checkKeyStore();
            if (isKeyStoreExists() && !isKeyStoreEmpty()) {
                chain = keyStore.getCertificateChain(alias);
            }
        } catch (Exception e) {
            log.error(e);
        }
        if (chain == null) {
            log.error("Could not get private key with alias " + alias + ".");
        }
        return chain;
    }

    /**
     * Utility method to extract an entity from a certificates subject DN
     * 
     * @param c certificate
     * @param entity entity to extract
     * @return entity value
     * @throws Exception
     */
    public static String getX509CertificateEntity(X509Certificate c, String entity) throws Exception {

        // This assumes the keystore returns the last certificate in the chain
        // (the
        // actual certifcate that is signed by a CA or untrusted cert

        Principal subjectPrincipal = c.getSubjectDN();

        StringTokenizer t = new StringTokenizer(subjectPrincipal.getName(), ",");
        while (t.hasMoreTokens()) {
            String e = t.nextToken().trim();
            String f = entity.trim() + "=";
            if (e.toLowerCase().startsWith(f.toLowerCase())) {
                return e.substring(f.length()).trim();
            }
        }

        return "";
        // This is causing problems with importing some certificates
        //throw new Exception("Unable to locate subject entity " + entity + " in " + subjectPrincipal.getName());
    }

    /**
     * Reload the key store this manager is managing
     */
    public void reloadKeystore() {
        keyStoreExists = false;
        keyStoreException = null;
        keyStoreEmpty = true;
        keyStore = null;
        

        try {

            File keystoreFile = getKeyStoreFile();
            InputStream in = null;

            if (keystoreFile.exists() && keystoreFile.canRead()) {
                keyStoreExists = true;
                keyStoreException = null;
                keyStoreEmpty = true;
                keyStore = null;
                try {
                    keyStore = KeyStore.getInstance(keyStoreType.getName());

                    String keystorePassword = getKeyStorePassword();
                    if (keystoreFile.length() != 0) {
                        in = new FileInputStream(keystoreFile);
                        keyStore.load(in, keystorePassword.toCharArray());
                        keyStoreEmpty = keyStore.size() == 0;

                    }
                } finally {
                    Util.closeStream(in);
                }
            } else {
                // No change
            }
        } catch (Exception e) {
            log.error("Failed to check key store.", e);
            keyStoreException = e;
        }
    }
    

    /**
     * Check the check store to see if it has been modified since it was last
     * loaded, loading it if it has changed
     */
    public void checkKeyStore() {
        initKeyStoreFile();
        try {
            File keystoreFile = getKeyStoreFile();
            if (keystoreFile.exists() && keystoreFile.canRead()) {
                Date fileLastModified = new Date(keystoreFile.lastModified());
                if (keystoreLastModified == null || !keystoreLastModified.equals(fileLastModified)) {
                    keystoreLastModified = fileLastModified;
                    reloadKeystore();
                } else {
                    // No change
                }
            } else {
                keyStore = null;
                keyStoreExists = false;
                keyStoreEmpty = true;
                keyStoreException = null;
            }
        } catch (Exception e) {
            log.error("Failed to check key store.", e);
            keyStoreException = e;
        }
    }

    /**
     * Import a key in PKCS12 key format
     * 
     * @param keyFile file to import
     * @param password password for key
     * @param alias alias for key
     * @throws Exception on any error
     */
    public void importPKCS12Key(File keyFile, String password, String alias) throws Exception {
        KeyStore kspkcs12 = KeyStore.getInstance("PKCS12");

        
        kspkcs12.load(new FileInputStream(keyFile), password.toCharArray());

        boolean hasTemp = false;
        if(isKeyStoreEmpty()) {

            if(isKeyStoreExists()) {                
                deleteKeyStore();
            }
            createKeyStore();
            
        	String dname = "cn=tmp, ou=tmp, o=tmp, l=tmp, st=tmp, c=GB";
        	createKey("temporary-key", dname);
        	hasTemp = true;
            
        	reloadKeystore();
        }
        
        try {
            for(Enumeration e = kspkcs12.aliases(); e.hasMoreElements(); ) {
                String a= (String)e.nextElement();
            }
	        Certificate c[] = kspkcs12.getCertificateChain(alias);
	
	        // Make sure we don't have a null chain
	        if (c == null)
	            c = new Certificate[] {};
	
	        Key key = kspkcs12.getKey(alias, password.toCharArray());
            if(key == null) {
                throw new Exception("No alias of '" + alias + "' in imported PKCS12 key file.");
            }
	        
	        this.keyStore.setKeyEntry(alias, key, getKeyStorePassword().toCharArray(), c);

        } finally {
            
            if(hasTemp || keyStore.containsAlias("temporary-key"))
                this.keyStore.deleteEntry("temporary-key");
            
            OutputStream out = null;
            try {
                out = new FileOutputStream(keyStoreFile.getAbsolutePath());
                getKeyStore().store(out, getKeyStorePassword().toCharArray());
            } finally {
                Util.closeStream(out);
            }            
            updateRepository(false);
        }
    }

    /**
     * Get the key store file this manager is managing
     * 
     * @return file
     */
    public File getKeyStoreFile() {
        return keyStoreFile;
    }

    /**
     * Create a new private key given an alias an DN. Note that the
     * DN will be escaped as required by RFC2253
     * 
     * @param alias alias
     * @param dname DN
     * @throws Exception on any error
     */
    public void createKey(String alias, String dname) throws Exception {
        checkKeyStore();
        if (!isKeyStoreExists()) {
            throw new Exception("Key store doesn't exists. Key cannot be created.");
        }
        /*
         * Because an empty keystore file is not valid, delete the key first
         * then let genkey create a new keystore
         */
        if (isKeyStoreEmpty()) {
            if (!getKeyStoreFile().delete()) {
                throw new Exception("Could not delete key store.");
            }
        }
        CommandRunner runner = null;
        try {
            String keyStorePassword = getKeyStorePassword();
            Vector v = new Vector();
            v.add(KEY_TOOL);
            v.add("-genkey");
            v.add("-alias");
            v.add(alias);
            v.add("-keyalg");
            v.add("RSA");

⌨️ 快捷键说明

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