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

📄 caadminsessionbean.java

📁 JAVA做的J2EE下CA认证系统 基于EJB开发
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
			// Revoke CA certificate			getCertificateStoreSession().revokeCertificate(admin, cadata.getCACertificate(), cadata.getCRLPublishers(), reason);             // Revoke all certificates generated by CA		    getCertificateStoreSession().revokeAllCertByCA(admin, issuerdn, RevokedCertInfo.REVOKATION_REASON_CACOMPROMISE);            getCRLCreateSession().run(admin, issuerdn);			cadata.setRevokationReason(reason);			cadata.setRevokationDate(new Date());			cadata.setStatus(SecConst.CA_REVOKED);			ca.setStatus(SecConst.CA_REVOKED);			ca.setCA(cadata);        }catch(Exception e){		   getLogSession().log(admin, caid, LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_ERROR_CAREVOKED,"An error occured when revoking  CA " + ca.getName(),e);           throw new EJBException(e);        }		getLogSession().log(admin, caid, LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_INFO_CAREVOKED,"CA " + ca.getName() + " revoked sucessfully, reason: " + reason);    } // revokeCA    /**     * @ejb.interface-method     */    public void upgradeFromOldCAKeyStore(Admin admin, String caname, byte[] p12file, char[] keystorepass,                                         char[] privkeypass, String privatekeyalias){        try{            // check authorization            if(admin.getAdminType() !=  Admin.TYPE_CACOMMANDLINE_USER)              getAuthorizationSession().isAuthorizedNoLog(admin,"/super_administrator");            // load keystore            java.security.KeyStore keystore=KeyStore.getInstance("PKCS12", "BC");            keystore.load(new java.io.ByteArrayInputStream(p12file),keystorepass);            Certificate[] certchain = KeyTools.getCertChain(keystore, privatekeyalias);            if (certchain.length < 1) {                log.error("Cannot load certificate chain with alias "+privatekeyalias);                throw new Exception("Cannot load certificate chain with alias "+privatekeyalias);            }            ArrayList certificatechain = new ArrayList();            for(int i=0;i< certchain.length;i++){                certificatechain.add(certchain[i]);            }            X509Certificate cacertificate = (X509Certificate) certchain[0];            PrivateKey p12privatekey = (PrivateKey) keystore.getKey( privatekeyalias, privkeypass);            PublicKey p12publickey = cacertificate.getPublicKey();            CAToken catoken = new SoftCAToken();            ((SoftCAToken) catoken).importKeysFromP12(p12privatekey, p12publickey);            // Create a X509CA			int signedby = CAInfo.SIGNEDBYEXTERNALCA;            int certprof = SecConst.CERTPROFILE_FIXED_SUBCA;			String description = "Imported external signed CA";            if(certchain.length == 1) {				if (verifyIssuer(cacertificate, cacertificate)) {					signedby = CAInfo.SELFSIGNED;					certprof = SecConst.CERTPROFILE_FIXED_ROOTCA;					description = "Imported root CA";				} else {					// A less strict strategy can be to assume certificate signed					// by an external CA. Useful if admin user forgot to create a full					// certificate chain in PKCS#12 package.					log.error("Cannot import CA " + cacertificate.getSubjectDN().getName()							+ ": certificate " + cacertificate.getSerialNumber()							+ " is not self-signed.");					throw new Exception("Cannot import CA "							+ cacertificate.getSubjectDN().getName()							+ ": certificate is not self-signed. Check "							+ "certificate chain in PKCS#12");				}			} else if (certchain.length > 1){				Collection cas = getAvailableCAs(admin);				Iterator iter = cas.iterator();				// Assuming certificate chain in forward direction (from target				// to most-trusted CA). Multiple CA chains can contains the				// issuer certificate; so only the chain where target certificate				// is the issuer will be selected.				while (iter.hasNext()) {					int caid = ((Integer)iter.next()).intValue();					CAInfo superCaInfo = getCAInfo(admin, caid);					Iterator i = superCaInfo.getCertificateChain().iterator();					if (i.hasNext()) {						X509Certificate superCaCert = (X509Certificate)i.next();						if (verifyIssuer(cacertificate, superCaCert)) {							signedby = caid;							description = "Imported sub CA";							break;						}					}				}					            }            // Create and active OSCP CA Service.            ArrayList extendedcaservices = new ArrayList();			extendedcaservices.add(			  new OCSPCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE,			                        "CN=OCSPSignerCertificate, " + cacertificate.getSubjectDN().toString(),			                        "",			                        2048,			                        OCSPCAServiceInfo.KEYALGORITHM_RSA));			int validity = (int)((cacertificate.getNotAfter().getTime() - cacertificate.getNotBefore().getTime()) / (24*3600*1000));            X509CAInfo cainfo = new X509CAInfo(cacertificate.getSubjectDN().toString(),                                               caname, SecConst.CA_ACTIVE,                                               "", certprof,                                               validity,                                               cacertificate.getNotAfter(), // Expiretime                                               CAInfo.CATYPE_X509,                                               signedby,                                               certificatechain,                                               catoken.getCATokenInfo(),                                               description,                                               -1, null, // revokationreason, revokationdate                                               "", // PolicyId                                               24, // CRLPeriod                                               new ArrayList(),                                               true, // Authority Key Identifier                                               false, // Authority Key Identifier Critical                                               true, // CRL Number                                               false, // CRL Number Critical                                               true, // Finish User			                                   extendedcaservices);            X509CA ca = new X509CA(cainfo);            ca.setCAToken(catoken);            ca.setCertificateChain(certificatechain);            //  Publish CA certificates.            int certtype = CertificateDataBean.CERTTYPE_SUBCA;            if(ca.getSignedBy() == CAInfo.SELFSIGNED)              certtype = CertificateDataBean.CERTTYPE_ROOTCA;            getSignSession().publishCACertificate(admin, ca.getCertificateChain(), ca.getCRLPublishers(), certtype);            // activate External CA Services            Iterator iter = cainfo.getExtendedCAServiceInfos().iterator();            while(iter.hasNext()){                ExtendedCAServiceInfo info = (ExtendedCAServiceInfo) iter.next();                if(info instanceof OCSPCAServiceInfo){                    try{                        ca.initExternalService(OCSPCAService.TYPE, ca);                        ArrayList ocspcertificate = new ArrayList();                        ocspcertificate.add(((OCSPCAServiceInfo) ca.getExtendedCAServiceInfo(OCSPCAService.TYPE)).getOCSPSignerCertificatePath().get(0));                        getSignSession().publishCACertificate(admin, ocspcertificate, ca.getCRLPublishers(), CertificateDataBean.CERTTYPE_ENDENTITY);                    }catch(Exception fe){                        getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_ERROR_CACREATED,"Couldn't Create ExternalCAService.",fe);                        throw new EJBException(fe);                    }                }            }                        // Store CA in database.            cadatahome.create(cainfo.getSubjectDN(), cainfo.getName(), SecConst.CA_ACTIVE, ca);            this.getCRLCreateSession().run(admin,cainfo.getSubjectDN());            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_INFO_CACREATED,"CA imported successfully from old P12 file, status: " + ca.getStatus());        }catch(Exception e){            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_ERROR_CACREATED,"An error occured when trying to import CA from old P12 file", e);            throw new EJBException(e);        }    } // upgradeFromOldCAKeyStore    /**     * @ejb.transaction type="Supports"     * @ejb.interface-method     */    public Collection getAllCACertificates(Admin admin){      ArrayList returnval = new ArrayList();      try{        Collection result = cadatahome.findAll();        Iterator iter = result.iterator();        while(iter.hasNext()){           CADataLocal cadatalocal = (CADataLocal) iter.next();           returnval.add(cadatalocal.getCA().getCACertificate());        }      }catch(javax.ejb.FinderException fe){}        catch(UnsupportedEncodingException uee){        	throw new EJBException(uee);        }      return returnval;    } // getAllCACertificates    /**     * @ejb.interface-method     */    public void activateCAToken(Admin admin, int caid, String authorizationcode) throws AuthorizationDeniedException, CATokenAuthenticationFailedException, CATokenOfflineException{       // Authorize        try{            getAuthorizationSession().isAuthorizedNoLog(admin,AvailableAccessRules.REGULAR_ACTIVATECA);        }catch(AuthorizationDeniedException ade){            getLogSession().log (admin, caid, LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,"Administrator isn't authorized to activate CA token.",ade);            throw new AuthorizationDeniedException("Administrator not authorized to activate CA token.");        }    	try{    		if(caid >=0 && caid <= CAInfo.SPECIALCAIDBORDER){    			getLogSession().log(admin, caid, LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_ERROR_CAEDITED,"Error when trying to activate CA with caid " + caid + ". CA activation not available.");    			throw new CATokenAuthenticationFailedException("Error when trying to activate CA with caid " + caid + ". CA activation not available.");    		}    		CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer(caid));    		if(cadata.getStatus() == SecConst.CA_OFFLINE){        		try {    				cadata.getCA().getCAToken().activate(authorizationcode);    				cadata.setStatus(SecConst.CA_ACTIVE);    				getLogSession().log(admin, caid, LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_INFO_CAEDITED,"CA " + cadata.getName() + " activated successfully.");    			} catch (IllegalKeyStoreException e) {                    throw new EJBException(e);    			} catch (UnsupportedEncodingException e) {                    throw new EJBException(e);    			}    		}else{				getLogSession().log(admin, caid, LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_ERROR_CAEDITED,"CA " + cadata.getName() + " must have the status 'offline' in order to be activated");				throw new CATokenAuthenticationFailedException("CA must have the status 'offline' in order to be activated");    		}    	}catch(javax.ejb.FinderException fe) {    	   getLogSession().log(admin, caid, LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_ERROR_CAEDITED,"Error when trying to activate CA with caid " + caid + ". CA could not be found.");    	   throw new EJBException(fe);    	}    }    /**     * @ejb.interface-method     */    public void deactivateCAToken(Admin admin, int caid) throws AuthorizationDeniedException, EjbcaException{       // Authorize        try{            getAuthorizationSession().isAuthorizedNoLog(admin,AvailableAccessRules.REGULAR_ACTIVATECA);        }catch(AuthorizationDeniedException ade){            getLogSession().log (admin, caid, LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,"Administrator isn't authorized to deactivate CA token.",ade);            throw new AuthorizationDeniedException("Administrator not authorized to deactivate CA token.");        }    	try{    		if(caid >=0 && caid <= CAInfo.SPECIALCAIDBORDER){                // This should never happen.    			getLogSession().log(admin, caid, LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_ERROR_CAEDITED,"Error when trying to deactivate CA with caid " + caid + ". CA deactivation not available.");    			throw new EjbcaException("Error when trying to deactivate CA with caid " + caid + ". CA deactivation not available.");    		}            CADataLocal cadata = cadatahome.findByPrimaryKey(new Integer(caid));            if(cadata.getStatus() == SecConst.CA_ACTIVE){            	try {            		cadata.getCA().getCAToken().deactivate();            		cadata.setStatus(SecConst.CA_OFFLINE);            		getLogSession().log(admin, caid, LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_INFO_CAEDITED,"CA " + cadata.getName() + "have been deactivated successfully.");            	} catch (IllegalKeyStoreException e) {            		throw new EJBException(e);            	} catch (UnsupportedEncodingException e) {            		throw new EJBException(e);            	}            }else{            	getLogSession().log(admin, caid, LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_ERROR_CAEDITED,"Error when trying to deactivate CA  " + cadata.getName() + ". CA is not active");            	throw new EjbcaException("Wrong user status of CA.");            }    	}catch(javax.ejb.FinderException fe) {    	   getLogSession().log(admin, caid, LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_ERROR_CAEDITED,"Error when trying to deactivate CA with caid " + caid + ". CA could not be found.");    	   throw new EJBException(fe);    	}    }    /**     * @ejb.interface-method     */    public boolea

⌨️ 快捷键说明

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