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

📄 rsasignsessionbean.java

📁 一套JAVA的CA证书签发系统.
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
            cacert.checkValidity();                             }catch(CertificateExpiredException e){            // Signers Certificate has expired.               cadata.setStatus(SecConst.CA_EXPIRED);              getLogSession().log(admin, caid, LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_ERROR_CREATECRL,"Signing CA " + cadata.getSubjectDN() + " has expired",e);            throw new EJBException("Signing CA " + cadata.getSubjectDN() + " has expired");             }catch(CertificateNotYetValidException e){          	 throw new EJBException(e);                       }                              ICertificateStoreSessionLocal certificateStore = storeHome.create();           // Get number of last CRL and increase by 1          int number = certificateStore.getLastCRLNumber(admin, ca.getSubjectDN()) + 1;          try{            crl = (X509CRL) ca.generateCRL(certs, number);          } catch(CATokenOfflineException ctoe) {            log.error("CA Token is Offline: ", ctoe);            cadata.setStatus(SecConst.CA_OFFLINE);              getLogSession().log(admin, cadata.getCAId().intValue(), LogEntry.MODULE_CA,  new java.util.Date(), null, null, LogEntry.EVENT_ERROR_CREATECRL,"Signing CA " + cadata.getSubjectDN() + " is offline.",ctoe);            throw new EJBException("Signing CA " + cadata.getSubjectDN() + " is offline.");          }          getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date(),null, null, LogEntry.EVENT_INFO_CREATECRL,"Number :" + number);                    // Store CRL in the database          String fingerprint = CertTools.getFingerprintAsString(cacert);          certificateStore.storeCRL(admin, crl.getEncoded(), fingerprint, number);          // Store crl in ca CRL publishers.          IPublisherSessionLocal pub = publishHome.create();          pub.storeCRL(admin, ca.getCRLPublishers(), crl.getEncoded(), fingerprint, number);                  } catch (Exception e) {                      getLogSession().log(admin, caid, LogEntry.MODULE_CA, new java.util.Date(),null, null, LogEntry.EVENT_ERROR_CREATECRL,"");                      throw new EJBException(e);        }        debug("<createCRL()");        return crl;    } // createCRL        /** Method that publishes the given CA certificate chain to the list of publishers.    * Is mainly used by CAAdminSessionBean when CA is created.    *  @see se.anatom.ejbca.ca.sign.ISignSessionRemote    */   public void publishCACertificate(Admin admin, Collection certificatechain, Collection usedpublishers, int certtype){       try{                            ICertificateStoreSessionLocal certificateStore = storeHome.create();                 Iterator certificates = certificatechain.iterator();           while(certificates.hasNext()){               Certificate cacert = (Certificate) certificates.next();                           //     Store CA certificate in the database                String fingerprint = CertTools.getFingerprintAsString((X509Certificate) cacert);                           if(certificateStore.findCertificateByFingerprint(admin, fingerprint) == null){                                                    certificateStore.storeCertificate(admin, cacert, "SYSTEMCA", fingerprint, CertificateData.CERT_ACTIVE, certtype);                }                  // Store cert in ca cert publishers.                IPublisherSessionLocal pub = publishHome.create();                if(usedpublishers != null)                  pub.storeCertificate(admin, usedpublishers, cacert, fingerprint, null , fingerprint, CertificateData.CERT_ACTIVE, certtype, null);        }       }catch(javax.ejb.CreateException ce){           throw new EJBException(ce);          }   }    private String getPassword(String initKey) throws Exception {        String password;        try {            password = (String)lookup(initKey, java.lang.String.class);        } catch (EJBException e) {            password = null;        }        if ( password == null ) {            debug(initKey+" password: ");            BufferedReader in            = new BufferedReader(new InputStreamReader(System.in));            return (in.readLine());        } else            return password;    }        private int sunKeyUsageToBC(boolean[] sku) {        int bcku = 0;        if (sku[0] == true)            bcku = bcku | X509KeyUsage.digitalSignature;        if (sku[1] == true)            bcku = bcku | X509KeyUsage.nonRepudiation;        if (sku[2] == true)            bcku = bcku | X509KeyUsage.keyEncipherment;        if (sku[3] == true)            bcku = bcku | X509KeyUsage.dataEncipherment;        if (sku[4] == true)            bcku = bcku | X509KeyUsage.keyAgreement;        if (sku[5] == true)            bcku = bcku | X509KeyUsage.keyCertSign;        if (sku[6] == true)            bcku = bcku | X509KeyUsage.cRLSign;        if (sku[7] == true)            bcku = bcku | X509KeyUsage.encipherOnly;        if (sku[8] == true)            bcku = bcku | X509KeyUsage.decipherOnly;        return bcku;    }            private UserAuthData authUser(Admin admin, String username, String password) throws ObjectNotFoundException, AuthStatusException, AuthLoginException {        // Authorize user and get DN        try {            IAuthenticationSessionLocal authSession = authHome.create();            return authSession.authenticateUser(admin, username, password);        } catch (CreateException e) {            log.error(e);            throw new EJBException(e);        }     } // authUser    private void finishUser(Admin admin, String username, String password) throws ObjectNotFoundException {        // Finnish user and set new status        try {            IAuthenticationSessionLocal authSession = authHome.create();            authSession.finishUser(admin, username, password);        } catch (CreateException e) {            log.error(e);            throw new EJBException(e);        }    } // finishUser    /** Creates the certificate, does NOT check any authorization on user, profiles or CA!      * This must be done earlier     *      * @param admin administrator performing this task     * @param data auth data for user to get the certificate     * @param ca the CA that will sign the certificate     * @param pk ther users public key to be put in the certificate     * @param keyusage requested key usage for the certificate, may be ignored by the CA     * @throws IllegalKeyException if the public key given is invalid     * @return Certificate that has been generated and signed by the CA     */    private Certificate createCertificate(Admin admin, UserAuthData data, CA ca, PublicKey pk, int keyusage) throws IllegalKeyException {        debug(">createCertificate(pk, ku)");                try {            // If the user is of type USER_INVALID, it cannot have any other type (in the mask)            if (data.getType() == SecConst.USER_INVALID) {                getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date(),data.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE,"User type is invalid, cannot create certificate for this user.");            } else {                ICertificateStoreSessionLocal certificateStore = storeHome.create();                // Retrieve the certificate profile this user should have                int certProfileId = data.getCertProfileId();                CertificateProfile certProfile = certificateStore.getCertificateProfile(admin, certProfileId);                // What if certProfile == null?                if (certProfile == null) {                    certProfileId = SecConst.CERTPROFILE_FIXED_ENDUSER;                    certProfile = certificateStore.getCertificateProfile(admin, certProfileId);                }                                // Check that CAid is among available CAs                boolean caauthorized = false;                Iterator iter = certProfile.getAvailableCAs().iterator();                while(iter.hasNext()){                  int next = ((Integer) iter.next()).intValue();                  if(next == data.getCAId() || next == CertificateProfile.ANYCA){                    caauthorized = true;                    }                                    }                                // Sign Session bean is only able to issue certificates with a end entity type certificate profile.                if(certProfile.getType() != CertificateProfile.TYPE_ENDENTITY){                  getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date(),data.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE,"Wrong type of Certificate Profile for end entity. Only End Entity Certificate Profiles can be issued by signsession bean.");                    throw new EJBException("Wrong type of Certificate Profile for end entity. Only End Entity Certificate Profiles can be issued by signsession bean.");                  }                                if(!caauthorized){                  getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date(),data.getUsername(), null, LogEntry.EVENT_ERROR_CREATECERTIFICATE,"End Entity data contains a CA which the Certificate Profile isn't authorized to use.");                    throw new EJBException("End Entity data contains a CA which the Certificate Profile isn't authorized to use.");                }                                                                log.debug("Using certificate profile with id "+certProfileId);                int keyLength;                try {                  keyLength = ((RSAPublicKey)pk).getModulus().bitLength();                } catch (ClassCastException e) {                  throw new                    IllegalKeyException("Unsupported public key (" +                                        pk.getClass().getName() +                                        "), only RSA keys are supported.");                }                log.debug("Keylength = "+keyLength); // bitBength() will return 1 less bit if BigInt i negative                if ( (keyLength < (certProfile.getMinimumAvailableBitLength()-1))                    || (keyLength > (certProfile.getMaximumAvailableBitLength())) ) {                        String msg = "Illegal key length "+keyLength;                        log.error(msg);                        throw new IllegalKeyException(msg);                    }                 X509Certificate   cert = (X509Certificate) ca.generateCertificate(data, pk, keyusage, certProfile);                                getLogSession().log(admin, data.getCAId(), LogEntry.MODULE_CA, new java.util.Date(),data.getUsername(), cert, LogEntry.EVENT_INFO_CREATECERTIFICATE,"");                debug("Generated certificate with SerialNumber '" + Hex.encode(cert.getSerialNumber().toByteArray())+"' for user '"+data.getUsername()+"'.");                debug(cert.toString());                                // Store certificate in the database                String fingerprint = CertTools.getFingerprintAsString(cert);                certificateStore.storeCertificate(admin, cert, data.getUsername(), fingerprint, CertificateData.CERT_ACTIVE, certProfile.getType());                // Store certificate in certificate profiles publishers.                IPublisherSessionLocal pub = publishHome.create();                if(certProfile.getPublisherList() != null)                  pub.storeCertificate(admin, certProfile.getPublisherList(), cert, data.getUsername(), data.getPassword(), fingerprint, CertificateData.CERT_ACTIVE, certProfile.getType(), data.getExtendedInformation());                                                                debug("<createCertificate(pk, ku)");                return cert;            }        } catch (IllegalKeyException ke) {            throw ke;        } catch (CATokenOfflineException ctoe) {        	        	ca.setStatus(SecConst.CA_OFFLINE);        	throw new EJBException("Error CA Token is Offline", ctoe);        }catch (Exception e) {            log.error(e);            throw new EJBException(e);        }        debug("<createCertificate(pk, ku)");        log.error("Invalid user type for user "+data.getUsername());        throw new EJBException("Invalid user type for user "+data.getUsername());        } // createCertificate    	/** 	 * Method used to perform the extended service	 */	public ExtendedCAServiceResponse extendedService(Admin admin, int caid, ExtendedCAServiceRequest request) 	  throws ExtendedCAServiceRequestException, IllegalExtendedCAServiceRequestException, ExtendedCAServiceNotActiveException, CADoesntExistsException{		// Get CA that will process request		CADataLocal cadata = null; 				ExtendedCAServiceResponse returnval = null;		try{					  cadata = cadatahome.findByPrimaryKey(new Integer(caid));		  returnval = cadata.getCA().extendedService(request);					}catch(javax.ejb.FinderException fe){			 			throw new CADoesntExistsException(fe);                   		}catch(UnsupportedEncodingException ue){			throw new EJBException(ue);		}		return returnval;	  		     	}        } //RSASignSessionBean

⌨️ 快捷键说明

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