Package org.ejbca.core.model.ca.caadmin

Examples of org.ejbca.core.model.ca.caadmin.CAInfo


      throw new EjbcaException(ErrorCode.INTERNAL_ERROR, e);
    }   
  }
 
  protected UserDataVO convertUserDataVOWS(Admin admin, UserDataVOWS userdata) throws CADoesntExistsException, EjbcaException, ClassCastException {
    final CAInfo cainfo = caAdminSession.getCAInfoOrThrowException(admin,userdata.getCaName());
    final int caid = cainfo.getCAId();
    if (caid == 0) {
      throw new CADoesntExistsException("Error CA " + userdata.getCaName() + " have caid 0, which is impossible.");
    }
   
    final int endentityprofileid = endEntityProfileSession.getEndEntityProfileId(admin,userdata.getEndEntityProfileName());
View Full Code Here


   * @see org.ejbca.core.protocol.ws.common.IEjbcaWS#caRenewCertRequest
   */
  protected void caCertResponse(EjbcaWSHelper ejbhelper, Admin admin, String caname, byte[] cert, List<byte[]> cachain, String keystorepwd)
    throws CADoesntExistsException, AuthorizationDeniedException, EjbcaException, ApprovalException, WaitingForApprovalException, CertPathValidatorException {
    try {
      CAInfo cainfo = caAdminSession.getCAInfo(admin, caname);
      // create response messages, for CVC certificates we use a regular X509ResponseMessage
      X509ResponseMessage msg = new X509ResponseMessage();
      msg.setCertificate(CertTools.getCertfromByteArray(cert));
      caAdminSession.receiveResponse(admin, cainfo.getCAId(), msg, cachain, keystorepwd);
    } catch (CertificateException e) {
            throw EjbcaWSHelper.getInternalException(e, null);
    }
  }
View Full Code Here

  /**
   * @see org.ejbca.core.protocol.ws.common.IEjbcaWS#caRenewCertRequest
   */
  protected byte[] caRenewCertRequest(EjbcaWSHelper ejbhelper, Admin admin, String caname, List<byte[]> cachain, boolean regenerateKeys, boolean usenextkey, boolean activatekey, String keystorepwd)
    throws CADoesntExistsException, AuthorizationDeniedException, EjbcaException, ApprovalException, WaitingForApprovalException, CertPathValidatorException {
    CAInfo cainfo = caAdminSession.getCAInfoOrThrowException(admin, caname);
    return caAdminSession.makeRequest(admin, cainfo.getCAId(), cachain, regenerateKeys, usenextkey, activatekey, keystorepwd);       
  }
View Full Code Here

  private PublicKey getCVPublicKey(Admin admin, java.security.cert.Certificate cert) throws CADoesntExistsException {
    PublicKey pk = cert.getPublicKey();
    if (pk instanceof PublicKeyEC) {
      // The public key of IS and DV certificate do not have any EC parameters so we have to do some magic to get a complete EC public key
      // First get to the CVCA certificate that has the parameters
      CAInfo info = caAdminSession.getCAInfoOrThrowException(admin, CertTools.getIssuerDN(cert).hashCode());
      Collection<java.security.cert.Certificate> cacerts = info.getCertificateChain();
      if (cacerts != null) {
        log.debug("Found CA certificate chain of length: "+cacerts.size());
        // Get the last cert in the chain, it is the CVCA cert
        Iterator<java.security.cert.Certificate> i = cacerts.iterator();
        java.security.cert.Certificate cvcacert = null;
View Full Code Here

            // status is NEW and password is correct.
          } else { // if (StringUtils.equals(holderRef, caRef))
            // Subject and issuerDN is CN=Mnemonic,C=Country
            String dn = "CN="+caRef.getMnemonic()+",C="+caRef.getCountry();
            log.debug("Authenticated request is not self signed, we will try to verify it using a CVCA certificate: "+dn);
            CAInfo info = caAdminSession.getCAInfoOrThrowException(admin, CertTools.stringToBCDNString(dn).hashCode());
            if (info != null) {
              Collection<java.security.cert.Certificate> certs = info.getCertificateChain();
              if (certs != null) {
                log.debug("Found "+certs.size()+" certificates in chain for CA with DN: "+dn);             
                Iterator<java.security.cert.Certificate> iterator = certs.iterator();
                if (iterator.hasNext()) {
                  // The CA certificate is first in chain
                  java.security.cert.Certificate cert = iterator.next();
                  if (log.isDebugEnabled()) {
                    log.debug("Trying to verify the outer signature with a CVCA certificate, fp: "+CertTools.getFingerprintAsString(cert));                   
                  }
                  try {
                    // The CVCA certificate always contains the full key parameters, no need to du any EC curve parameter magic here
                    authreq.verify(cert.getPublicKey());
                    log.debug("Verified outer signature");
                    verifiedOuter = true;
                    // Yes we did it, we can move on to the next step because the outer signature was actually created with some old certificate
                    if (!ejbhelper.checkValidityAndSetUserPassword(admin, cert, username, password)) {
                      // If the CA certificate was not valid, we are not happy                 
                      String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), "CA certificate not valid for CA: "+info.getCAId());             
                      log.info(msg);
                      throw new AuthorizationDeniedException(msg);
                    }             
                  } catch (InvalidKeyException e) {
                    String msg = intres.getLocalizedMessage("cvc.error.outersignature", holderRef.getConcatenated(), e.getMessage());             
View Full Code Here

    ApprovalRequest ar = null;
    boolean approvalSuccessfullStep1 = false;
    boolean isRejectedStep1 = false;

    // Get Significant user Id
    final CAInfo significantcAInfo;
    final ArrayList<java.security.cert.Certificate> genCertificates = new ArrayList<java.security.cert.Certificate>();
    final IPatternLogger logger = TransactionLogger.getPatternLogger();
        logAdminName(admin,logger);
    try {
      significantcAInfo = caAdminSession.getCAInfoOrThrowException(intAdmin, userDataWS.getCaName());
    if(significantcAInfo == null){
      throw EjbcaWSHelper.getEjbcaException("Error the given CA : " + userDataWS.getCaName() + " couldn't be found.",
          logger, ErrorCode.CA_NOT_EXISTS, null);
    }
   
      UserDataVO userDataVO = userAdminSession.findUser(intAdmin, userDataWS.getUsername());
      if(userDataVO != null){
        endEntityProfileId = userDataVO.getEndEntityProfileId();
        userExists = true;
      }else{
        endEntityProfileId = endEntityProfileSession.getEndEntityProfileId(intAdmin, userDataWS.getEndEntityProfileName());         
        if(endEntityProfileId == 0){
          throw EjbcaWSHelper.getEjbcaException("Error given end entity profile : " + userDataWS.getEndEntityProfileName() +" couldn't be found",
            logger, ErrorCode.EE_PROFILE_NOT_EXISTS, null);
        }
      }
     
     
      if(ejbhelper.isAdmin()){     
       
                if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_CREATECERTIFICATE)) {
                    Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_CREATECERTIFICATE, null);
                }
                if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.HARDTOKEN_ISSUEHARDTOKENS)) {
                    Authorizer.throwAuthorizationException(admin, AccessRulesConstants.HARDTOKEN_ISSUEHARDTOKENS, null);
                }
                if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.CAPREFIX + significantcAInfo.getCAId())) {
                    throw new AuthorizationDeniedException("Admin " + admin + " was not authorized to resource " + AccessRulesConstants.CAPREFIX
                            + significantcAInfo.getCAId());
                }
                if (userExists) {
                    if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_EDITENDENTITY)) {
                        Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_EDITENDENTITY, null);
                    }
                    endEntityProfileId = userDataVO.getEndEntityProfileId();
                    if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                            + AccessRulesConstants.EDIT_RIGHTS)) {
                        Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                + AccessRulesConstants.EDIT_RIGHTS, null);
                    }

                    if (overwriteExistingSN) {
                        if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY)) {
                            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY, null);
                        }
                        if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                + AccessRulesConstants.REVOKE_RIGHTS)) {
                            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                    + AccessRulesConstants.REVOKE_RIGHTS, null);
                        }
                    }
                } else {
                    if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_CREATEENDENTITY)) {
                        Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_CREATEENDENTITY, null);
                    }
                    if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                            + AccessRulesConstants.CREATE_RIGHTS)) {
                        Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                + AccessRulesConstants.CREATE_RIGHTS, null);
                    }
                    if (overwriteExistingSN) {
                        if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY)) {
                            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.REGULAR_REVOKEENDENTITY, null);
                        }
                        if (!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                + AccessRulesConstants.REVOKE_RIGHTS)) {
                            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + endEntityProfileId
                                    + AccessRulesConstants.REVOKE_RIGHTS, null);
                        }
                    }
                }

      }else{
        if(WebServiceConfiguration.getApprovalForGenTokenCertificates()){
          ar = new GenerateTokenApprovalRequest(userDataWS.getUsername(), userDataWS.getSubjectDN(), hardTokenDataWS.getLabel(),admin,null,WebServiceConfiguration.getNumberOfRequiredApprovals(),significantcAInfo.getCAId(),endEntityProfileId);
          int status = ApprovalDataVO.STATUS_REJECTED;          
          try{
            status = approvalSession.isApproved(admin, ar.generateApprovalId(), 1);
            approvalSuccessfullStep1 =  status == ApprovalDataVO.STATUS_APPROVED;
            if(approvalSuccessfullStep1){
              ApprovalDataVO approvalDataVO = approvalSession.findNonExpiredApprovalRequest(intAdmin, ar.generateApprovalId());
              String originalDN = ((GenerateTokenApprovalRequest) approvalDataVO.getApprovalRequest()).getDN();
              userDataWS.setSubjectDN(originalDN); // replace requested DN with original DN to make sure nothing have changed.
            }
            isRejectedStep1 = status == ApprovalDataVO.STATUS_REJECTED;
            if(   status == ApprovalDataVO.STATUS_EXPIREDANDNOTIFIED
               || status == ApprovalDataVO.STATUS_EXPIRED){
              throw new ApprovalException("");
            }
          }catch(ApprovalException e){
            approvalSession.addApprovalRequest(admin, ar, globalConfigurationSession.getCachedGlobalConfiguration(admin));
            throw new WaitingForApprovalException("Approval request with id " + ar.generateApprovalId() + " have been added for approval.",ar.generateApprovalId());
          }
        }else{
          throw new AuthorizationDeniedException();
        }
      }

    if(ar != null && isRejectedStep1){
      throw new ApprovalRequestExecutionException("The approval for id " + ar.generateApprovalId() + " have been rejected.");
    }
   
    if(ar != null && !approvalSuccessfullStep1){
      throw new WaitingForApprovalException("The approval for id " + ar.generateApprovalId() + " have not yet been approved", ar.generateApprovalId());
    }
   
    if(ar != null){
      admin = new ApprovedActionAdmin(admin.getAdminInformation().getX509Certificate(), admin.getUsername(), admin.getEmail());
    }
   
      hardTokenExists = hardTokenSession.existsHardToken(admin, hardTokenDataWS.getHardTokenSN());
      if(hardTokenExists){
        if(overwriteExistingSN){
          // fetch all old certificates and revoke them.
          Collection<java.security.cert.Certificate> currentCertificates = hardTokenSession.findCertificatesInHardToken(admin, hardTokenDataWS.getHardTokenSN());
          HardTokenData currentHardToken = hardTokenSession.getHardToken(admin, hardTokenDataWS.getHardTokenSN(), false);
          Iterator<java.security.cert.Certificate> iter = currentCertificates.iterator();
          while(iter.hasNext()){
            java.security.cert.X509Certificate nextCert = (java.security.cert.X509Certificate) iter.next();
            try {
              userAdminSession.revokeCert(admin, CertTools.getSerialNumber(nextCert), CertTools.getIssuerDN(nextCert), RevokedCertInfo.REVOCATION_REASON_SUPERSEDED);
            } catch (AlreadyRevokedException e) {
              // Ignore previously revoked certificates
            } catch (FinderException e) {
                            throw EjbcaWSHelper.getEjbcaException("Error revoking old certificate, the user : " + currentHardToken.getUsername() + " of the old certificate couldn't be found in database.",
                                                    logger, ErrorCode.USER_NOT_FOUND, null);
            }
          }

        }else{
          throw new HardTokenExistsException("Error hard token with sn " + hardTokenDataWS.getHardTokenSN() + " already exists.");
        }

      }


      if(revokePreviousCards){
        List<HardTokenDataWS> htd = getHardTokenDatas(admin,userDataWS.getUsername(), false, true, logger);
        Iterator<HardTokenDataWS> htdIter = htd.iterator();

        while(htdIter.hasNext()) {
          HardTokenDataWS toRevoke = htdIter.next();
          try{
              if(hardTokenDataWS.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD) && toRevoke.getLabel() != null && !toRevoke.getLabel().equals(HardTokenConstants.LABEL_TEMPORARYCARD)){

                // Token have extended key usage MS Logon, don't revoke it
                Iterator<java.security.cert.Certificate> revokeCerts = hardTokenSession.findCertificatesInHardToken(admin, toRevoke.getHardTokenSN()).iterator();

                while(revokeCerts.hasNext()){
                  X509Certificate next = (X509Certificate) revokeCerts.next();              
                  try{
                    if(WebServiceConfiguration.getSuspendAllCertificates() || next.getExtendedKeyUsage() == null || !next.getExtendedKeyUsage().contains(KeyPurposeId.id_kp_smartcardlogon.getId())){
                      userAdminSession.revokeCert(admin,next.getSerialNumber(), CertTools.getIssuerDN(next), RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD);
                    }
                  }catch(CertificateParsingException e){
                    log.error(e);
                  } catch (FinderException e) {
                    log.error(e);
                 
                }
           

            }else{
              revokeToken(admin, toRevoke.getHardTokenSN(), RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED, logger);
            }
          }catch(AlreadyRevokedException e){
            // Do nothing
          }
        }
      }
   
    try{
      // Check if the userdata exist and edit/add it depending on which
      String password = PasswordGeneratorFactory.getInstance(PasswordGeneratorFactory.PASSWORDTYPE_ALLPRINTABLE).getNewPassword(8, 8);
      UserDataVO userData = ejbhelper.convertUserDataVOWS(admin, userDataWS);
      userData.setPassword(password);
      if(userExists){
        userAdminSession.changeUser(admin, userData, true);
      }else{
        userAdminSession.addUser(admin, userData, true);
      }

      Date bDate = new Date(System.currentTimeMillis() - (10 * 60 * 1000));
     
      Iterator<TokenCertificateRequestWS> iter = tokenRequests.iterator();
      while(iter.hasNext()){
        TokenCertificateRequestWS next = iter.next();

        int certificateProfileId = certificateProfileSession.getCertificateProfileId(admin, next.getCertificateProfileName());
        if(certificateProfileId == 0){
                    EjbcaWSHelper.getEjbcaException("Error the given Certificate Profile : " + next.getCertificateProfileName() + " couldn't be found.",
                                      logger, ErrorCode.CERT_PROFILE_NOT_EXISTS, null);
        }
       
        Date eDate = null;
       
        if(next.getValidityIdDays() != null ){
          try{
            long validity = Long.parseLong(next.getValidityIdDays());
            eDate = new Date(System.currentTimeMillis() + (validity  * 3600 *24 * 1000));
          }catch (NumberFormatException e){
                        EjbcaWSHelper.getEjbcaException("Error : Validity in Days must be a number",
                                          logger, ErrorCode.BAD_VALIDITY_FORMAT, null);
          }
        }
       
        CAInfo cAInfo = caAdminSession.getCAInfo(admin, next.getCAName());
        if(cAInfo == null){
          throw EjbcaWSHelper.getEjbcaException("Error the given CA : " + next.getCAName() + " couldn't be found.",
            logger, ErrorCode.CA_NOT_EXISTS, null);
        }

        if(!authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.CAPREFIX + cAInfo.getCAId())) {
            Authorizer.throwAuthorizationException(admin, AccessRulesConstants.CAPREFIX + cAInfo.getCAId(), null);
        }
        if(next.getType() == HardTokenConstants.REQUESTTYPE_PKCS10_REQUEST){           
          userData.setCertificateProfileId(certificateProfileId);
          userData.setCAId(cAInfo.getCAId());
          userData.setPassword(password);
          userData.setStatus(UserDataConstants.STATUS_NEW);
          userAdminSession.changeUser(admin, userData, false);
          PKCS10RequestMessage pkcs10req = new PKCS10RequestMessage(next.getPkcs10Data());
          java.security.cert.Certificate cert;
          if(eDate == null){
              cert =  signSession.createCertificate(admin,userData.getUsername(),password, pkcs10req.getRequestPublicKey());
          }else{
            cert =  signSession.createCertificate(admin,userData.getUsername(),password, pkcs10req.getRequestPublicKey(), -1, bDate, eDate);
          }
         
          genCertificates.add(cert);
          retval.add(new TokenCertificateResponseWS(new Certificate(cert)));
        }else
          if(next.getType() == HardTokenConstants.REQUESTTYPE_KEYSTORE_REQUEST){

            if(!next.getTokenType().equals(HardTokenConstants.TOKENTYPE_PKCS12)){
              throw EjbcaWSHelper.getEjbcaException("Unsupported Key Store Type : " + next.getTokenType() + " only " + HardTokenConstants.TOKENTYPE_PKCS12 + " is supported",
                                                        logger, ErrorCode.NOT_SUPPORTED_KEY_STORE, null);
            }
            KeyPair keys = KeyTools.genKeys(next.getKeyspec(), next.getKeyalg());               
            userData.setCertificateProfileId(certificateProfileId);
            userData.setCAId(cAInfo.getCAId());
            userData.setPassword(password);
            userData.setStatus(UserDataConstants.STATUS_NEW);
            userAdminSession.changeUser(admin, userData, true);
            X509Certificate cert;
            if(eDate == null){
                cert =  (X509Certificate) signSession.createCertificate(admin,userData.getUsername(),password, keys.getPublic());
            }else{
              cert =  (X509Certificate) signSession.createCertificate(admin,userData.getUsername(),password, keys.getPublic(), -1, bDate, eDate);
            }
           
            genCertificates.add(cert);     
            // Generate Keystore
            // Fetch CA Cert Chain.         
            Collection<java.security.cert.Certificate> chain =  caAdminSession.getCAInfo(admin, cAInfo.getCAId()).getCertificateChain();
            String alias = CertTools.getPartFromDN(CertTools.getSubjectDN(cert), "CN");
            if (alias == null){
              alias = userData.getUsername();
            }               
            java.security.KeyStore pkcs12 = KeyTools.createP12(alias, keys.getPrivate(), cert, chain);
View Full Code Here

        logCert = CertificateHelper.getCertificate(certificate.getCertificateData());
      }

      int caId = admin.getCaId();
      if(cAName  != null){
        CAInfo cAInfo = caAdminSession.getCAInfoOrThrowException(admin, cAName);
        caId = cAInfo.getCAId();
      }

      String comment = type + " : " + msg;
      logSession.log(admin, caId, LogConstants.MODULE_CUSTOM, new Date(), username, (X509Certificate) logCert, event, comment);
    } catch (CertificateException e) {
View Full Code Here

    EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, certificateProfileSession, certificateStoreSession, endEntityProfileSession, hardTokenSession, userAdminSession);
    Admin admin = ejbhelper.getAdmin();
        final IPatternLogger logger = TransactionLogger.getPatternLogger();
        logAdminName(admin,logger);
    try {
      CAInfo info = caAdminSession.getCAInfoOrThrowException(admin, caname);
      if (info.getStatus() == SecConst.CA_WAITING_CERTIFICATE_RESPONSE){
        return retval;
      }
         Collection<java.security.cert.Certificate> certs = info.getCertificateChain();
      Iterator<java.security.cert.Certificate> iter = certs.iterator();
      while (iter.hasNext()){
        retval.add(new Certificate (iter.next ()));
      }
    } catch (CertificateEncodingException e) {
View Full Code Here

                log.trace(">run()");
        }
        if (ca == null) {
            throw new EJBException("No CA specified.");
        }
        CAInfo cainfo = ca.getCAInfo();
        int caid = cainfo.getCAId();
        String ret = null;
        try {
            final String caCertSubjectDN; // DN from the CA issuing the CRL to be used when searching for the CRL in the database.
            {
                final Collection<Certificate> certs = cainfo.getCertificateChain();
                final Certificate cacert = !certs.isEmpty() ? certs.iterator().next(): null;
                caCertSubjectDN = cacert!=null ? CertTools.getSubjectDN(cacert) : null;
            }
            // We can not create a CRL for a CA that is waiting for certificate response
            if ( caCertSubjectDN!=null && cainfo.getStatus()==SecConst.CA_ACTIVE )  {
                long crlperiod = cainfo.getCRLPeriod();
                // Find all revoked certificates for a complete CRL
                Collection<RevokedCertInfo> revcerts = certificateStoreSession.listRevokedCertInfo(admin, caCertSubjectDN, -1);
                if (log.isDebugEnabled()) {
                        log.debug("Found "+revcerts.size()+" revoked certificates.");
                }
                // Go through them and create a CRL, at the same time archive expired certificates
                Date now = new Date();
                Date check = new Date(now.getTime() - crlperiod);
                Iterator<RevokedCertInfo> iter = revcerts.iterator();
                while (iter.hasNext()) {
                        RevokedCertInfo data = iter.next();
                        // We want to include certificates that was revoked after the last CRL was issued, but before this one
                        // so the revoked certs are included in ONE CRL at least. See RFC5280 section 3.3.
                        if ( data.getExpireDate().before(check) ) {
                                // Certificate has expired, set status to archived in the database
                                certificateStoreSession.setArchivedStatus(Admin.getInternalAdmin(), data.getCertificateFingerprint());
                        } else {
                                Date revDate = data.getRevocationDate();
                                if (revDate == null) {
                                        data.setRevocationDate(now);
                                        CertificateData certdata = CertificateData.findByFingerprint(entityManager, data.getCertificateFingerprint());
                                        if (certdata == null) {
                                                throw new FinderException("No certificate with fingerprint " + data.getCertificateFingerprint());
                                        }
                                        // Set revocation date in the database
                                        certdata.setRevocationDate(now);
                                }
                        }
                }
                // a full CRL
                byte[] crlBytes = createCRL(admin, ca, revcerts, -1);
                if (crlBytes != null) {
                        ret = CertTools.getFingerprintAsString(crlBytes);                      
                }
                // This is logged in the database by SignSession
                String msg = intres.getLocalizedMessage("createcrl.createdcrl", cainfo.getName(), cainfo.getSubjectDN());              
                log.info(msg);
                // This debug logging is very very heavy if you have large CRLs. Please don't use it :-)
//              if (log.isDebugEnabled()) {
//              X509CRL crl = CertTools.getCRLfromByteArray(crlBytes);
//              debug("Created CRL with expire date: "+crl.getNextUpdate());
//              FileOutputStream fos = new FileOutputStream("c:\\java\\srvtestcrl.der");
//              fos.write(crl.getEncoded());
//              fos.close();
//              }
            } else {
                String msg = intres.getLocalizedMessage("createcrl.errornotactive", cainfo.getName(), Integer.valueOf(caid), cainfo.getStatus());                                                     
                log.info(msg);                 
            }
        } catch (CATokenOfflineException e) {
            throw e;           
        } catch (Exception e) {
View Full Code Here

    @Override
    public byte[] runDeltaCRL(Admin admin, CA ca, int baseCrlNumber, long baseCrlCreateTime) throws CATokenOfflineException {
                if (ca == null) {
                        throw new EJBException("No CA specified.");
                }
                CAInfo cainfo = ca.getCAInfo();
        if (log.isTraceEnabled()) {
                log.trace(">runDeltaCRL: "+cainfo.getSubjectDN());
        }
        byte[] crlBytes = null;
        final int caid = cainfo.getCAId();
        try {
                final String caCertSubjectDN; {
                    final Collection<Certificate> certs = cainfo.getCertificateChain();
                    final Certificate cacert = !certs.isEmpty() ? certs.iterator().next(): null;
                caCertSubjectDN = cacert!=null ? CertTools.getSubjectDN(cacert) : null;
            }
                if (caCertSubjectDN!=null && cainfo instanceof X509CAInfo) { // Only create CRLs for X509 CAs
                        if ( (baseCrlNumber == -1) && (baseCrlCreateTime == -1) ) {
                                CRLInfo basecrlinfo = crlSession.getLastCRLInfo(admin, caCertSubjectDN, false);
                                baseCrlCreateTime = basecrlinfo.getCreateDate().getTime();
                                baseCrlNumber = basecrlinfo.getLastCRLNumber();                                
                        }
                        // Find all revoked certificates
                        Collection<RevokedCertInfo> revcertinfos = certificateStoreSession.listRevokedCertInfo(admin, caCertSubjectDN, baseCrlCreateTime);
                                if (log.isDebugEnabled()) {
                                        log.debug("Found "+revcertinfos.size()+" revoked certificates.");
                                }
                        // Go through them and create a CRL, at the same time archive expired certificates
                        ArrayList<RevokedCertInfo> certs = new ArrayList<RevokedCertInfo>();
                        Iterator<RevokedCertInfo> iter = revcertinfos.iterator();
                        while (iter.hasNext()) {
                                RevokedCertInfo ci = iter.next();
                                if (ci.getRevocationDate() == null) {
                                        ci.setRevocationDate(new Date());
                                }
                                certs.add(ci);
                        }
                        // create a delta CRL
                        crlBytes = createCRL(admin, ca, certs, baseCrlNumber);
                        X509CRL crl = CertTools.getCRLfromByteArray(crlBytes);
                                if (log.isDebugEnabled()) {
                                        log.debug("Created delta CRL with expire date: "+crl.getNextUpdate());
                                }
                }
        } catch (CATokenOfflineException e) {
            throw e;           
        } catch (Exception e) {
                logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(),null, null, LogConstants.EVENT_ERROR_CREATECRL,e.getMessage());
                throw new EJBException(e);
        }
        if (log.isTraceEnabled()) {
                log.trace("<runDeltaCRL: "+cainfo.getSubjectDN());
        }
                return crlBytes;
    }
View Full Code Here

TOP

Related Classes of org.ejbca.core.model.ca.caadmin.CAInfo

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.