Package org.ejbca.core.model.ca.catoken

Examples of org.ejbca.core.model.ca.catoken.CATokenContainer


    byte[] ret = null;
    // Create a CVC request.
    // No outer signature on this self signed request
    KeyPair keyPair;
    try {
      CATokenContainer catoken = getCAToken();
      keyPair = new KeyPair(catoken.getPublicKey(signatureKeyPurpose), catoken.getPrivateKey(signatureKeyPurpose));
      if (keyPair == null) {
        throw new IllegalArgumentException("Keys for key purpose "+signatureKeyPurpose+" does not exist.");
      }
      String subject = getCAInfo().getSubjectDN();
      String country = CertTools.getPartFromDN(subject, "C");
      String mnemonic = CertTools.getPartFromDN(subject, "CN");
      String seq = getCAToken().getCATokenInfo().getKeySequence();
      if (signatureKeyPurpose == SecConst.CAKEYPURPOSE_CERTSIGN_NEXT) {
        // See if we have a next sequence to put in the holder reference instead of the current one,
        // since we are using the next key we should use the next sequence
        String propdata = catoken.getCATokenInfo().getProperties();
        Properties prop = new Properties();
        if (propdata != null) {
          prop.load(new ByteArrayInputStream(propdata.getBytes()));         
        }
        String nextSequence = (String)prop.get(ICAToken.NEXT_SEQUENCE_PROPERTY);
        // Only use next sequence if we also use previous key
        if (nextSequence != null) {
          seq = nextSequence;
          log.debug("Using next sequence in holderRef: "+seq);
        } else {
          log.debug("Using current sequence in holderRef, although we are using the next key...no next sequence was found: "+seq);       
        }
      }
      if (seq == null) {
        log.info("No sequence found in ca token info, using random 5 number sequence.");
        seq = RandomStringUtils.randomNumeric(5);
      }
      if (seq.length() > 5) {
        log.info("Sequence "+seq+" is too long, only using first 5.");
        seq = seq.substring(0, 4);
      }
      if (seq.length() < 5) {
        log.info("Sequence "+seq+" is too short, padding with zeroes.");
        for (int i = seq.length(); i < 5; i++) {
          seq = "0"+seq;         
        }
      }
      HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, seq);
      CAReferenceField caRef = null;
      if (cacert != null) {
        if (cacert instanceof CardVerifiableCertificate) {
          CardVerifiableCertificate cvcacert = (CardVerifiableCertificate) cacert;
          try {
            HolderReferenceField href = cvcacert.getCVCertificate().getCertificateBody().getHolderReference();
            caRef = new CAReferenceField(href.getCountry(), href.getMnemonic(), href.getSequence());
            log.debug("Using caRef from the CA certificate: "+caRef.getConcatenated());         
          } catch (NoSuchFieldException e) {
            log.debug("CA certificate does not contain a Holder reference to use as CARef in request.");
          }         
        } else {
          log.debug("CA certificate is not a CardVerifiableCertificate.");         
        }
      } else {
        caRef = new CAReferenceField(holderRef.getCountry(), holderRef.getMnemonic(), holderRef.getSequence());       
        log.debug("No CA cert, using caRef from the holder itself: "+caRef.getConcatenated());         
      }
      log.debug("Creating request with signature alg: "+signAlg+", using provider "+catoken.getProvider());
      CVCertificate request = CertificateGenerator.createRequest(keyPair, signAlg, caRef, holderRef, catoken.getProvider());
      ret = request.getDEREncoded();
    } catch (IllegalKeyStoreException e) {
            throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
View Full Code Here


      CardVerifiableCertificate cacert = (CardVerifiableCertificate)getCACertificate();
      if (cacert == null) {
        // if we don't have a CA certificate, we can't sign any request, just return it
        return request;
      }
      CATokenContainer catoken = getCAToken();
      // Get either the current or the previous signing key for signing this request
      int key = SecConst.CAKEYPURPOSE_CERTSIGN;
      if (usepreviouskey) {
        log.debug("Using previous CertSign key to sign request");
        key = SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS;
      } else {
        log.debug("Using current CertSign key to sign request");
      }
      KeyPair keyPair = new KeyPair(catoken.getPublicKey(key), catoken.getPrivateKey(key));
      String signAlg = getCAToken().getCATokenInfo().getSignatureAlgorithm();
      // Create the CA reference, should be from signing certificates holder field
      HolderReferenceField caHolder = cacert.getCVCertificate().getCertificateBody().getHolderReference();
      String sequence = caHolder.getSequence();
      // See if we have a previous sequence to put in the CA reference instead of the same as we have from the request
      String propdata = catoken.getCATokenInfo().getProperties();
      Properties prop = new Properties();
      if (propdata != null) {
        prop.load(new ByteArrayInputStream(propdata.getBytes()));         
      }
      String previousSequence = (String)prop.get(ICAToken.PREVIOUS_SEQUENCE_PROPERTY);
      // Only use previous sequence if we also use previous key
      if ( (previousSequence != null) && (usepreviouskey) ) {
        sequence = previousSequence;
        log.debug("Using previous sequence in caRef: "+sequence);
      } else {
        log.debug("Using current sequence in caRef: "+sequence);       
      }
      // Set the CA reference field for the authentication signature
      CAReferenceField caRef = new CAReferenceField(caHolder.getCountry(), caHolder.getMnemonic(), sequence);

      CVCertificate cvcert = null;
      try {
        byte[] binbytes = request;
        try {
          // We don't know if this is a PEM or binary certificate or request request so we first try to
          // decode it as a PEM certificate, and if it's not we try it as a PEM request and finally as a binary request
          Collection<Certificate> col = CertTools.getCertsFromPEM(new ByteArrayInputStream(request));
          Certificate cert = col.iterator().next();
          if (cert != null) {
            binbytes = cert.getEncoded();
          }
        } catch (Exception e) {
          log.debug("This is not a PEM certificate?: "+e.getMessage());
          try {
            binbytes = RequestMessageUtils.getRequestBytes(request);
          } catch (Exception e2) {
            log.debug("This is not a PEM request?: "+e2.getMessage());           
          }
        }
        // This can be either a CV certificate, a CV certificate request, or an authenticated request that we should re-sign
        CVCObject parsedObject;
        parsedObject = CertificateParser.parseCVCObject(binbytes);
        if (parsedObject instanceof CVCertificate) {
          cvcert = (CVCertificate) parsedObject;
          log.debug("This is a reqular CV request, or cert.");         
        } else if (parsedObject instanceof CVCAuthenticatedRequest) {
          CVCAuthenticatedRequest authreq = (CVCAuthenticatedRequest)parsedObject;
          cvcert = authreq.getRequest();
          log.debug("This is an authenticated CV request, we will overwrite the old authentication with a new.");         
        }
      } catch (ParseException e) {
              String msg = intres.getLocalizedMessage("cvc.error.notcvcrequest");
        log.info(msg, e);
        return request;
      } catch (ClassCastException e) {
              String msg = intres.getLocalizedMessage("cvc.error.notcvcrequest");
        log.info(msg, e);
        return request;
      }
      // Check if the input was a CVCA certificate, which is the same CVCA as this. If all is true we should create a CVCA link certificate
      // instead of an authenticated request
      CardVerifiableCertificate cvccert = new CardVerifiableCertificate(cvcert);
      HolderReferenceField cvccertholder = cvccert.getCVCertificate().getCertificateBody().getHolderReference();
      AuthorizationRoleEnum authRole = null;
      AccessRightEnum rights = null;
      try {
        authRole = cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate().getAuthorizationField().getRole();         
         rights = cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate().getAuthorizationField().getAccessRight();
      } catch (NoSuchFieldException e) {
        log.debug("No AuthorizationRoleEnum or AccessRightEnum, this is not a CV certificate so we can't make a link certificate: "+e.getMessage());
       
      }
      if (createlinkcert && (authRole != null) && (rights != null)) {
        log.debug("We will create a link certificate.");
        String msg = intres.getLocalizedMessage("cvc.info.createlinkcert", cvccertholder.getConcatenated(), caRef.getConcatenated());
        log.info(msg);
        PublicKey pk = cvccert.getPublicKey();
        Date validFrom = cvccert.getCVCertificate().getCertificateBody().getValidFrom();
        Date validTo = cvccert.getCVCertificate().getCertificateBody().getValidTo();
        // Generate a new certificate with the same contents as the passed in certificate, but with new caRef and signature
        CVCertificate retcert = CertificateGenerator.createCertificate(pk, keyPair.getPrivate(), signAlg, caRef, cvccertholder, authRole, rights, validFrom, validTo, catoken.getProvider());
        ret = retcert.getDEREncoded();
        log.debug("Signed a CardVerifiableCertificate CardVerifiableCertificate.");
      } else {
        log.debug("Creating authenticated request with signature alg: "+signAlg+", using provider "+catoken.getProvider());
        CVCAuthenticatedRequest authreq = CertificateGenerator.createAuthenticatedRequest(cvcert, keyPair, signAlg, caRef, catoken.getProvider());
        ret = authreq.getDEREncoded();       
        log.debug("Signed a CardVerifiableCertificate request and returned a CVCAuthenticatedRequest.");
      }
    } catch (IllegalKeyStoreException e) {
      throw new RuntimeException(e);
View Full Code Here

          case CertificateProfile.CVC_ACCESS_DG4: accessRights = AccessRightEnum.READ_ACCESS_DG4; break;
          case CertificateProfile.CVC_ACCESS_DG3DG4: accessRights = AccessRightEnum.READ_ACCESS_DG3_AND_DG4; break;
          case CertificateProfile.CVC_ACCESS_NONE: accessRights = AccessRightEnum.READ_ACCESS_NONE; break;
        }
        // Generate the CVC certificate using Keijos library
        CATokenContainer catoken = getCAToken();
        String sigAlg = catoken.getCATokenInfo().getSignatureAlgorithm();
        log.debug("Creating CV certificate with algorithm "+sigAlg+", using provider "+catoken.getProvider()+", public key algorithm from CVC request must match this algorithm.");
        log.debug("CARef: "+caRef.getConcatenated()+"; holderRef: "+holderRef.getConcatenated());
        CVCertificate cvc = CertificateGenerator.createCertificate(publicKey, catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN),
            sigAlg, caRef, holderRef, authRole, accessRights, val.getNotBefore(), val.getNotAfter(), catoken.getProvider());

        if (log.isDebugEnabled()) {
            log.debug("Certificate: "+cvc.toString());
            log.debug("Certificate bytes: "+new String(Base64.encode(cvc.getDEREncoded())));         
        }
View Full Code Here

          ca = getCAFromRequest(admin, req);
        } else {
          ca = caSession.getCA(admin, suppliedUserData.getCAId()); // Take the CAId from the supplied userdata, if any
        }
        try {
            CATokenContainer catoken = ca.getCAToken();
           
            // See if we need some key material to decrypt request
            if (req.requireKeyInfo()) {
                // You go figure...scep encrypts message with the public CA-cert
                req.setKeyInfo(ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getJCEProvider());
            }
            // Verify the request
            if (req.verify() == false) {
              String msg = intres.getLocalizedMessage("signsession.popverificationfailed");
              logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
                throw new SignRequestSignatureException(msg);
            }
           
            if (ca.isUseUserStorage() && req.getUsername() == null) {
              String msg = intres.getLocalizedMessage("signsession.nouserinrequest", req.getRequestDN());
              logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
                throw new SignRequestException(msg);
                //ret.setFailInfo(FailInfo.BAD_REQUEST);
                //ret.setStatus(ResponseStatus.FAILURE);
            } else if (ca.isUseUserStorage() && req.getPassword() == null) {
              String msg = intres.getLocalizedMessage("signsession.nopasswordinrequest");
                logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
                throw new SignRequestException(msg);
            } else {       
              ResponseStatus status = ResponseStatus.SUCCESS;
              FailInfo failInfo = null;
              String failText = null;
                Certificate cert = null;
              try {
            // If we haven't done so yet, authenticate user. (Only if we store UserData for this CA.)
                if (ca.isUseUserStorage()) {
                    data = authUser(admin, req.getUsername(), req.getPassword());
                } else {
                  data = suppliedUserData;
                }
                    PublicKey reqpk = req.getRequestPublicKey();
                    if (reqpk == null) {
                        logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, intres.getLocalizedMessage("signsession.nokeyinrequest"));
                        throw new InvalidKeyException("Key is null!");
                    }
                    // We need to make sure we use the users registered CA here
                    if (data.getCAId() != ca.getCAId()) {
                      failText = intres.getLocalizedMessage("signsession.wrongauthority", Integer.valueOf(ca.getCAId()), Integer.valueOf(data.getCAId()));
                        status = ResponseStatus.FAILURE;
                        failInfo = FailInfo.WRONG_AUTHORITY;
                        logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, failText);
                    }

                    if (status.equals(ResponseStatus.SUCCESS)) {
                      Date notBefore = req.getRequestValidityNotBefore(); // Optionally requested validity
                      Date notAfter = req.getRequestValidityNotAfter(); // Optionally requested validity
                      X509Extensions exts = req.getRequestExtensions(); // Optionally requested extensions
                      int keyusage = -1;
                      if (exts != null) {
                          if (log.isDebugEnabled()) {
                            log.debug("we have extensions, see if we can override KeyUsage by looking for a KeyUsage extension in request");
                          }
                        X509Extension ext = exts.getExtension(X509Extensions.KeyUsage);
                        if (ext != null) {
                          ASN1OctetString os = ext.getValue();
                          ByteArrayInputStream bIs = new ByteArrayInputStream(os.getOctets());
                          ASN1InputStream dIs = new ASN1InputStream(bIs);
                          DERObject dob = dIs.readObject();
                          DERBitString bs = DERBitString.getInstance(dob);
                          keyusage = bs.intValue();                                                           
                          if (log.isDebugEnabled()) {
                            log.debug("We have a key usage request extension: "+keyusage);
                          }
                        }
                      }
              String sequence = null;
              byte[] ki = req.getRequestKeyInfo();
              if ( (ki != null) && (ki.length > 0) ) {
                  sequence = new String(ki);               
              }
                      cert = createCertificate(admin, data, req.getRequestX509Name(), ca, reqpk, keyusage, notBefore, notAfter, exts, sequence);
                    }
              } catch (ObjectNotFoundException oe) {
                // If we didn't find the entity return error message
                log.error("User not found: ", oe);
                  failText = intres.getLocalizedMessage("signsession.nosuchuser", req.getUsername());
                    status = ResponseStatus.FAILURE;
                    failInfo = FailInfo.INCORRECT_DATA;
                    logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, failText);
              }
               
                //Create the response message with all nonces and checks etc
                ret = req.createResponseMessage(responseClass, req, ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider());
       
        if ( (cert == null) && (status == ResponseStatus.SUCCESS) ) {
          status = ResponseStatus.FAILURE;
          failInfo = FailInfo.BAD_REQUEST;
                } else {
View Full Code Here

    public IResponseMessage createRequestFailedResponse(Admin admin, IRequestMessage req,  Class responseClass) throws  AuthLoginException, AuthStatusException, IllegalKeyException, CADoesntExistsException, SignRequestSignatureException, SignRequestException, CATokenOfflineException {
      log.trace(">createRequestFailedResponse(IRequestMessage)");
        IResponseMessage ret = null;           
        CA ca = getCAFromRequest(admin, req);
        try {
            CATokenContainer catoken = ca.getCAToken();
            // See if we need some key material to decrypt request
            if (req.requireKeyInfo()) {
                // You go figure...scep encrypts message with the public CA-cert
                req.setKeyInfo(ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider());
            }
            // Verify the request
            if (req.verify() == false) {
              String msg = intres.getLocalizedMessage("signsession.popverificationfailed");
              logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, intres.getLocalizedMessage("signsession.popverificationfailed"));
                throw new SignRequestSignatureException(msg);
            }
            //Create the response message with all nonces and checks etc
            ret = req.createResponseMessage(responseClass, req, ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider());
            ret.setStatus(ResponseStatus.FAILURE);
            ret.setFailInfo(FailInfo.BAD_REQUEST);
            ret.create();
        } catch (IllegalKeyStoreException e) {
            throw new IllegalKeyException(e);
View Full Code Here

    public IRequestMessage decryptAndVerifyRequest(Admin admin, IRequestMessage req) throws ObjectNotFoundException, AuthStatusException, AuthLoginException, IllegalKeyException, CADoesntExistsException, SignRequestException, SignRequestSignatureException {
      log.trace(">decryptAndVerifyRequest(IRequestMessage)");
        // Get CA that will receive request
        CA ca = getCAFromRequest(admin, req);
        try {
            CATokenContainer catoken = ca.getCAToken();
            // See if we need some key material to decrypt request
            if (req.requireKeyInfo()) {
                // You go figure...scep encrypts message with the public CA-cert
                req.setKeyInfo(ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider());
            }
            // Verify the request
            if (req.verify() == false) {
              String msg = intres.getLocalizedMessage("signsession.popverificationfailed");
              logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
View Full Code Here

        log.trace(">getCRL(IRequestMessage)");
        IResponseMessage ret = null;
        // Get CA that will receive request
        CA ca = getCAFromRequest(admin, req);
        try {
            CATokenContainer catoken = ca.getCAToken();
            if (ca.getStatus() != SecConst.CA_ACTIVE) {
              String msg = intres.getLocalizedMessage("signsession.canotactive", ca.getSubjectDN());
              logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_GETLASTCRL, msg);
                throw new EJBException(msg);
            }
            // See if we need some key material to decrypt request
            if (req.requireKeyInfo()) {
                // You go figure...scep encrypts message with the public CA-cert
                req.setKeyInfo(ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider());
            }
            //Create the response message with all nonces and checks etc
            ret = req.createResponseMessage(responseClass, req, ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider());
           
            // Get the Full CRL, don't even bother digging into the encrypted CRLIssuerDN...since we already
            // know that we are the CA (SCEP is soooo stupid!)
            final String certSubjectDN = CertTools.getSubjectDN(ca.getCACertificate());
            byte[] crl = crlSession.getLastCRL(admin, certSubjectDN, false);
View Full Code Here

TOP

Related Classes of org.ejbca.core.model.ca.catoken.CATokenContainer

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.