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

📄 batchmakep12.java

📁 JAVA做的J2EE下CA认证系统 基于EJB开发
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/************************************************************************* *                                                                       * *  EJBCA: The OpenSource Certificate Authority                          * *                                                                       * *  This software is free software; you can redistribute it and/or       * *  modify it under the terms of the GNU Lesser General Public           * *  License as published by the Free Software Foundation; either         * *  version 2.1 of the License, or any later version.                    * *                                                                       * *  See terms of license at gnu.org.                                     * *                                                                       * *************************************************************************/package se.anatom.ejbca.batch;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.security.GeneralSecurityException;import java.security.KeyPair;import java.security.KeyStore;import java.security.KeyStoreException;import java.security.NoSuchAlgorithmException;import java.security.NoSuchProviderException;import java.security.UnrecoverableKeyException;import java.security.cert.Certificate;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.Collection;import java.util.Iterator;import javax.naming.Context;import javax.naming.NamingException;import org.apache.log4j.Logger;import se.anatom.ejbca.SecConst;import se.anatom.ejbca.ca.sign.ISignSessionHome;import se.anatom.ejbca.ca.sign.ISignSessionRemote;import se.anatom.ejbca.common.UserDataVO;import se.anatom.ejbca.keyrecovery.IKeyRecoverySessionHome;import se.anatom.ejbca.keyrecovery.IKeyRecoverySessionRemote;import se.anatom.ejbca.keyrecovery.KeyRecoveryData;import se.anatom.ejbca.log.Admin;import se.anatom.ejbca.ra.IUserAdminSessionHome;import se.anatom.ejbca.ra.IUserAdminSessionRemote;import se.anatom.ejbca.ra.UserAdminConstants;import se.anatom.ejbca.ra.UserDataConstants;import se.anatom.ejbca.ra.raadmin.IRaAdminSessionHome;import se.anatom.ejbca.ra.raadmin.IRaAdminSessionRemote;import se.anatom.ejbca.util.CertTools;import se.anatom.ejbca.util.InitialContextBuilder;import se.anatom.ejbca.util.KeyTools;import se.anatom.ejbca.util.P12toPEM;/** * This class generates keys and request certificates for all users with status NEW. The result is * generated PKCS12-files. * * @version $Id: BatchMakeP12.java,v 1.57 2005/05/09 19:01:47 anatom Exp $ */public class BatchMakeP12 {    /**     * For logging     */    private static final Logger log = Logger.getLogger(BatchMakeP12.class);    /**     * Where created P12-files are stored, default username.p12     */    private String mainStoreDir = "";    private IUserAdminSessionHome adminhome;    private IRaAdminSessionHome raadminhome;    private ISignSessionHome signhome;    private IKeyRecoverySessionHome keyrecoveryhome;    private Admin administrator;    private boolean usekeyrecovery = false;    /**     * Gets an initial context     *     * @return new initial context     * @throws NamingException if we can't find jndi name     */    public static Context getInitialContext() throws NamingException {        log.debug(">GetInitialContext");        // jndi.properties must exist in classpath        Context ctx = InitialContextBuilder.getInstance().getInitialContext();        log.debug("<GetInitialContext");        return ctx;    }    /**     * Creates new BatchMakeP12 object.     *     * @throws javax.naming.NamingException     * @throws CreateException     * @throws RemoteException     */    public BatchMakeP12()            throws javax.naming.NamingException, javax.ejb.CreateException, java.rmi.RemoteException,            java.io.IOException {        log.debug(">BatchMakeP12:");        administrator = new Admin(Admin.TYPE_BATCHCOMMANDLINE_USER);        // Bouncy Castle security provider        CertTools.installBCProvider();        Context jndiContext = getInitialContext();        Object obj = jndiContext.lookup("UserAdminSession");        adminhome = (IUserAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, IUserAdminSessionHome.class);        obj = jndiContext.lookup("RaAdminSession");        raadminhome = (IRaAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, IRaAdminSessionHome.class);        obj = jndiContext.lookup("RSASignSession");        signhome = (ISignSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, ISignSessionHome.class);        IRaAdminSessionRemote raadmin = raadminhome.create();        usekeyrecovery = (raadmin.loadGlobalConfiguration(administrator)).getEnableKeyRecovery();        if (usekeyrecovery) {            obj = jndiContext.lookup("KeyRecoverySession");            keyrecoveryhome = (IKeyRecoverySessionHome) javax.rmi.PortableRemoteObject.narrow(obj, IKeyRecoverySessionHome.class);        }        log.debug("<BatchMakeP12:");    } // BatchMakeP12    /**     * Gets full CA-certificate chain.     *     * @return Certificate[]     */    private Certificate[] getCACertChain(int caid)            throws Exception {        log.debug(">getCACertChain()");        ISignSessionRemote ss = signhome.create();        Certificate[] chain = (Certificate[]) ss.getCertificateChain(administrator, caid).toArray(new Certificate[0]);        log.debug("<getCACertChain()");        return chain;    } // getCACertificate    /**     * Sets the location where generated P12-files will be stored, full name will be:     * mainStoreDir/username.p12.     *     * @param dir existing directory     */    public void setMainStoreDir(String dir) {        mainStoreDir = dir;    }    /**     * Stores keystore.     *     * @param ks         KeyStore     * @param username   username, the owner of the keystore     * @param kspassword the password used to protect the peystore     * @param createJKS  if a jks should be created     * @param createPEM  if pem files should be created     * @throws IOException if directory to store keystore cannot be created     */    private void storeKeyStore(KeyStore ks, String username, String kspassword, boolean createJKS,                               boolean createPEM)            throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException,            NoSuchProviderException, CertificateException {        log.debug(">storeKeyStore: ks=" + ks.toString() + ", username=" + username);        // Where to store it?        if (mainStoreDir == null) {            throw new IOException("Can't find directory to store keystore in.");        }        String keyStoreFilename = mainStoreDir + "/" + username;        if (createJKS) {            keyStoreFilename += ".jks";        } else {            keyStoreFilename += ".p12";        }        // If we should also create PEM-files, do that        if (createPEM) {            String PEMfilename = mainStoreDir + "/pem";            P12toPEM p12topem = new P12toPEM(ks, kspassword, true);            p12topem.setExportPath(PEMfilename);            p12topem.createPEM();        } else {            FileOutputStream os = new FileOutputStream(keyStoreFilename);            ks.store(os, kspassword.toCharArray());        }        log.debug("Keystore stored in " + keyStoreFilename);        log.debug("<storeKeyStore: ks=" + ks.toString() + ", username=" + username);    } // storeKeyStore    /**     * Creates files for a user, sends request to CA, receives reploy and creates P12.     *     * @param username  username     * @param password  user's password     * @param id        of CA used to issue the keystore certificates     * @param rsaKeys   a previously generated RSA keypair     * @param createJKS if a jks should be created     * @param createPEM if pem files should be created     * @param savekeys  if generated keys should be saved in db (key recovery)     * @throws Exception if the certificate is not an X509 certificate     * @throws Exception if the CA-certificate is corrupt     * @throws Exception if verification of certificate or CA-cert fails     * @throws Exception if keyfile (generated by ourselves) is corrupt     */    private void createUser(String username, String password, int caid, KeyPair rsaKeys, boolean createJKS, boolean createPEM, boolean savekeys)            throws Exception {        log.debug(">createUser: username=" + username);        // Send the certificate request to the CA        ISignSessionRemote ss = signhome.create();        X509Certificate cert = (X509Certificate) ss.createCertificate(administrator, username,                password, rsaKeys.getPublic());        //System.out.println("issuer " + CertTools.getIssuerDN(cert) + ", " + cert.getClass().getName());        // Make a certificate chain from the certificate and the CA-certificate        Certificate[] cachain = getCACertChain(caid);        // Verify CA-certificate        if (CertTools.isSelfSigned((X509Certificate) cachain[cachain.length - 1])) {            try {                cachain[cachain.length - 1].verify(cachain[cachain.length - 1].getPublicKey());            } catch (GeneralSecurityException se) {                throw new Exception("RootCA certificate does not verify");            }        } else {            throw new Exception("RootCA certificate not self-signed");        }        // Verify that the user-certificate is signed by our CA        try {            cert.verify(cachain[0].getPublicKey());        } catch (GeneralSecurityException se) {            throw new Exception("Generated certificate does not verify using CA-certificate.");        }        if (usekeyrecovery && savekeys) {            // Save generated keys to database.            IKeyRecoverySessionRemote keyrecoverysession = keyrecoveryhome.create();            keyrecoverysession.addKeyRecoveryData(administrator, cert, username, rsaKeys);        }        // Use CN if as alias in the keystore, if CN is not present use username        String alias = CertTools.getPartFromDN(CertTools.getSubjectDN(cert), "CN");        if (alias == null) alias = username;        // Store keys and certificates in keystore.        KeyStore ks = null;        if (createJKS) {            ks = KeyTools.createJKS(alias, rsaKeys.getPrivate(), password, cert, cachain);        } else {            ks = KeyTools.createP12(alias, rsaKeys.getPrivate(), cert, cachain);        }        storeKeyStore(ks, username, password, createJKS, createPEM);

⌨️ 快捷键说明

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