Examples of CATokenContainer


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

    public void importCAFromKeys(Admin admin, String caname, String keystorepass, Certificate[] signatureCertChain, PublicKey p12PublicSignatureKey,
            PrivateKey p12PrivateSignatureKey, PrivateKey p12PrivateEncryptionKey, PublicKey p12PublicEncryptionKey) throws Exception,
            CATokenAuthenticationFailedException, CATokenOfflineException, IllegalKeyStoreException, CreateException {
        // Transform into token
        SoftCATokenInfo sinfo = new SoftCATokenInfo();
        CATokenContainer catoken = new CATokenContainerImpl(sinfo, CertTools.stringToBCDNString(
                StringTools.strip(CertTools.getSubjectDN(signatureCertChain[0]))).hashCode());
        catoken.importKeys(keystorepass, p12PrivateSignatureKey, p12PublicSignatureKey, p12PrivateEncryptionKey, p12PublicEncryptionKey, signatureCertChain);
        log.debug("CA-Info: " + catoken.getCATokenInfo().getSignatureAlgorithm() + " " + catoken.getCATokenInfo().getEncryptionAlgorithm());
        // Identify the key algorithms for extended CA services, OCSP, XKMS, CMS
        String keyAlgorithm = AlgorithmTools.getKeyAlgorithm(p12PublicSignatureKey);
        String keySpecification = AlgorithmTools.getKeySpecification(p12PublicSignatureKey);
        if (keyAlgorithm == null || keyAlgorithm == AlgorithmConstants.KEYALGORITHM_RSA) {
            keyAlgorithm = AlgorithmConstants.KEYALGORITHM_RSA;
View Full Code Here

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

        hardcatokeninfo.setEncryptionAlgorithm(AlgorithmConstants.SIGALG_SHA1_WITH_RSA);
        hardcatokeninfo.setProperties(catokenproperties);
        hardcatokeninfo.setSignatureAlgorithm(signatureAlgorithm);

        CATokenInfo catokeninfo = hardcatokeninfo;
        CATokenContainer catoken = new CATokenContainerImpl(catokeninfo, CertTools.stringToBCDNString(
                StringTools.strip(CertTools.getSubjectDN(signatureCertChain[0]))).hashCode());
        catoken.activate(catokenpassword);

        String keyAlgorithm = AlgorithmConstants.KEYALGORITHM_RSA;
        String keySpecification = "2048";
        // Do the general import
        importCA(admin, caname, catokenpassword, signatureCertChain, catoken, keyAlgorithm, keySpecification);
View Full Code Here

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

        log.trace(">exportCAKeyStore");
        try {
          CAData cadata = CAData.findByNameOrThrow(entityManager, caname);
          CA thisCa = cadata.getCA();
            // Make sure we are not trying to export a hard or invalid token
            CATokenContainer thisCAToken = thisCa.getCAToken();
            int tokentype = thisCAToken.getCATokenType();
            if (tokentype != CATokenConstants.CATOKENTYPE_P12) {
                throw new Exception("Cannot export anything but a soft token.");
            }
            // Check authorization
            if (admin.getAdminType() != Admin.TYPE_CACOMMANDLINE_USER && !authorizationSession.isAuthorizedNoLog(admin, AccessRulesConstants.ROLE_SUPERADMINISTRATOR)) {
                Authorizer.throwAuthorizationException(admin, AccessRulesConstants.ROLE_SUPERADMINISTRATOR, null);
            }
            // Fetch keys
            // This is a way of verifying the password. If activate fails, we
            // will get an exception and the export will not proceed
            thisCAToken.activate(keystorepass);

            PrivateKey p12PrivateEncryptionKey = thisCAToken.getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT);
            PublicKey p12PublicEncryptionKey = thisCAToken.getPublicKey(SecConst.CAKEYPURPOSE_KEYENCRYPT);
            PrivateKey p12PrivateCertSignKey = thisCAToken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN);
            PrivateKey p12PrivateCRLSignKey = thisCAToken.getPrivateKey(SecConst.CAKEYPURPOSE_CRLSIGN);
            if (!p12PrivateCertSignKey.equals(p12PrivateCRLSignKey)) {
                throw new Exception("Assertion of equal signature keys failed.");
            }
            // Proceed with the export
            byte[] ret = null;
            String format = null;
            if (thisCa.getCAType() == CAInfo.CATYPE_CVC) {
                log.debug("Exporting private key with algorithm: " + p12PrivateCertSignKey.getAlgorithm() + " of format: " + p12PrivateCertSignKey.getFormat());
                format = p12PrivateCertSignKey.getFormat();
                ret = p12PrivateCertSignKey.getEncoded();
            } else {
                log.debug("Exporting PKCS12 keystore");
                format = "PKCS12";
                KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
                keystore.load(null, keystorepass.toCharArray());
                // Load keys into keystore
                Certificate[] certificateChainSignature = (Certificate[]) thisCa.getCertificateChain().toArray(new Certificate[0]);
                Certificate[] certificateChainEncryption = new Certificate[1];
                // certificateChainSignature[0].getSigAlgName(),
                // generate dummy certificate for encryption key.
                certificateChainEncryption[0] = CertTools.genSelfCertForPurpose("CN=dummy2", 36500, null, p12PrivateEncryptionKey, p12PublicEncryptionKey,
                        thisCAToken.getCATokenInfo().getEncryptionAlgorithm(), true, X509KeyUsage.keyEncipherment);
                log.debug("Exporting with sigAlgorithm " + CertTools.getSignatureAlgorithm(certificateChainSignature[0]) + "encAlgorithm="
                        + thisCAToken.getCATokenInfo().getEncryptionAlgorithm());
                if (keystore.isKeyEntry(privateSignatureKeyAlias)) {
                    throw new Exception("Key \"" + privateSignatureKeyAlias + "\"already exists in keystore.");
                }
                if (keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                    throw new Exception("Key \"" + privateEncryptionKeyAlias + "\"already exists in keystore.");
View Full Code Here

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

            // Make sure we are not trying to export a hard or invalid token
            if (thisCa.getCAType() != CATokenConstants.CATOKENTYPE_P12) {
                throw new Exception("Cannot extract fingerprint from a non-soft token (" + thisCa.getCAType() + ").");
            }
            // Fetch keys
            CATokenContainer thisCAToken = thisCa.getCAToken();
            PrivateKey p12PrivateEncryptionKey = thisCAToken.getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT);
            PrivateKey p12PrivateCertSignKey = thisCAToken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN);
            PrivateKey p12PrivateCRLSignKey = thisCAToken.getPrivateKey(SecConst.CAKEYPURPOSE_CRLSIGN);
            MessageDigest md = MessageDigest.getInstance("SHA1");
            md.update(p12PrivateEncryptionKey.getEncoded());
            md.update(p12PrivateCertSignKey.getEncoded());
            md.update(p12PrivateCRLSignKey.getEncoded());
            return new String(Hex.encode(md.digest()));
View Full Code Here

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

              throw new SignRequestSignatureException(msg1);
            }
            gen.addSigner(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), (X509Certificate)getCACertificate(), CMSSignedGenerator.DIGEST_SHA1);
            gen.addCertificatesAndCRLs(certs);
            CMSSignedData s = null;
            CATokenContainer catoken = getCAToken();
            CATokenInfo tokeninfo = getCAInfo().getCATokenInfo();
            if (catoken != null && !(tokeninfo instanceof NullCATokenInfo)) {
              log.debug("createPKCS7: Provider="+catoken.getProvider()+" using algorithm "+getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN).getAlgorithm());
              s = gen.generate(msg, true, catoken.getProvider());
            } else {
              String msg1 = "CA Token does not exist!";
              log.debug(msg);
              throw new SignRequestSignatureException(msg1);
            }
View Full Code Here

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

          converter = new X509DefaultEntryConverter();
        }
        X509Name x509dn = CertTools.stringToBcX509Name(getSubjectDN(), converter, getUseLdapDNOrder());
        PKCS10CertificationRequest req;
    try {
      CATokenContainer catoken = getCAToken();
      KeyPair keyPair = new KeyPair(catoken.getPublicKey(signatureKeyPurpose), catoken.getPrivateKey(signatureKeyPurpose));
      if (keyPair == null) {
        throw new IllegalArgumentException("Keys for key purpose "+signatureKeyPurpose+" does not exist.");
      }
      req = new PKCS10CertificationRequest(signAlg, x509dn, keyPair.getPublic(), attrset, keyPair.getPrivate(), catoken.getProvider());
      log.trace("<createRequest");
          return req.getEncoded();
    } catch (CATokenOfflineException e) {
      throw e;
    } catch (Exception e) {
View Full Code Here

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

   * @see CA#signRequest(Collection, String)
   */
  public byte[] signRequest(byte[] request, boolean usepreviouskey, boolean createlinkcert) throws CATokenOfflineException {
    byte[] ret = null;
    try {
      CATokenContainer catoken = getCAToken();
      byte[] binbytes = request;
      X509Certificate cert = null;
      try {
        // We don't know if this is a PEM or binary certificate so we first try to
        // decode it as a PEM certificate, and if it's not we try it as a binary certificate
        Collection<Certificate> col = CertTools.getCertsFromPEM(new ByteArrayInputStream(request));
        cert = (X509Certificate)col.iterator().next();
        if (cert != null) {
          binbytes = cert.getEncoded();
        }
      } catch (Exception e) {
        log.debug("This is not a PEM certificate?: "+e.getMessage());
      }
      cert = (X509Certificate)CertTools.getCertfromByteArray(binbytes);
      // Check if the input was a CA certificate, which is the same CA as this. If all is true we should create a NewWithOld link-certificate
      X509Certificate cacert = (X509Certificate)getCACertificate();
      if (CertTools.getSubjectDN(cert).equals(CertTools.getSubjectDN(cacert))) {
              PublicKey currentCaPublicKey = catoken.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN);
        cert.verify(currentCaPublicKey); // Throws SignatureException if verify fails
        if (createlinkcert && usepreviouskey) {
          log.debug("We will create a link certificate.");
          X509CAInfo info = (X509CAInfo)getCAInfo();
              UserDataVO cadata = new UserDataVO("nobody", info.getSubjectDN(), info.getSubjectDN().hashCode(), info.getSubjectAltName(), null,
                  0,0,0,  info.getCertificateProfileId(), null, null, 0, 0, null);
         
          CertificateProfile certProfile = new RootCACertificateProfile();
              if((info.getPolicies() != null) && (info.getPolicies().size() > 0)) {
                certProfile.setUseCertificatePolicies(true);
                certProfile.setCertificatePolicies(info.getPolicies());
              }       
                PublicKey previousCaPublicKey = catoken.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
                PrivateKey previousCaPrivateKey = catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
                String provider = catoken.getProvider();
              String sequence = catoken.getCATokenInfo().getKeySequence(); // get from CAtoken to make sure it is fresh
              Certificate retcert = generateCertificate(cadata, null, cert.getPublicKey(),-1, cert.getNotBefore(), cert.getNotAfter(), certProfile, null, sequence, previousCaPublicKey, previousCaPrivateKey, provider);
          log.debug("Signed an X509Certificate: '"+cadata.getDN()+"'.");
          String msg = intres.getLocalizedMessage("cvc.info.createlinkcert", cadata.getDN(), cadata.getDN());
          log.info(msg);
          ret = retcert.getEncoded();
View Full Code Here

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

            CertificateProfile certProfile,
            X509Extensions extensions,
            String sequence) throws Exception {
      // Before we start, check if the CA is off-line, we don't have to waste time
      // one the stuff below of we are off-line. The line below will throw CATokenOfflineException of CA is offline
      CATokenContainer catoken = getCAToken();
        PublicKey caPublicKey = catoken.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN);
        PrivateKey caPrivateKey = catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN);
        String provider = catoken.getProvider();
      return generateCertificate(subject, requestX509Name, publicKey, keyusage, notBefore, notAfter, certProfile, extensions, sequence, caPublicKey, caPrivateKey, provider);
    }
View Full Code Here

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

          logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CACREATED, msg);
          throw new CAExistsException(msg);
        }
        // Create CAToken
        CATokenInfo catokeninfo = cainfo.getCATokenInfo();
        CATokenContainer catoken = new CATokenContainerImpl(catokeninfo, cainfo.getCAId());
        String authCode = catokeninfo.getAuthenticationCode();
        authCode = getDefaultKeyStorePassIfSWAndEmpty(authCode, catokeninfo);
        if (catokeninfo instanceof SoftCATokenInfo) {
            try {
                // There are two ways to get the authentication code:
                // 1. The user provided one when creating the CA on the create
                // CA page
                // 2. We use the system default password
                boolean renew = false;
                catoken.generateKeys(authCode, renew, true);
            } catch (Exception e) {
                String msg = intres.getLocalizedMessage("caadmin.errorcreatetoken");
                logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CACREATED, msg, e);
                throw new EJBException(e);
            }
        }
        try {
            catoken.activate(authCode);
        } catch (CATokenAuthenticationFailedException ctaf) {
            String msg = intres.getLocalizedMessage("caadmin.errorcreatetokenpin");
            logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CACREATED, msg, ctaf);
            throw ctaf;
        } catch (CATokenOfflineException ctoe) {
            String msg = intres.getLocalizedMessage("error.catokenoffline", cainfo.getName());
            logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CACREATED, msg, ctoe);
            throw ctoe;
        }

        // Create CA
        CA ca = null;
        // The certificate profile used for the CAs certificate
        CertificateProfile certprofile = certificateProfileSession.getCertificateProfile(admin, cainfo.getCertificateProfileId());
        // AltName is not implemented for all CA types
        String caAltName = null;
        // X509 CA is the normal type of CA
        if (cainfo instanceof X509CAInfo) {
            log.info("Creating an X509 CA");
            X509CAInfo x509cainfo = (X509CAInfo) cainfo;
            // Create X509CA
            ca = new X509CA(x509cainfo);
            X509CA x509ca = (X509CA) ca;
            ca.setCAToken(catoken);

            // getCertificateProfile
            if ((x509cainfo.getPolicies() != null) && (x509cainfo.getPolicies().size() > 0)) {
                certprofile.setUseCertificatePolicies(true);
                certprofile.setCertificatePolicies(x509cainfo.getPolicies());
            } else if (certprofile.getUseCertificatePolicies()) {
                x509ca.setPolicies(certprofile.getCertificatePolicies());
            }
            caAltName = x509cainfo.getSubjectAltName();
        } else {
            // CVC CA is a special type of CA for EAC electronic passports
            log.info("Creating a CVC CA");
            CVCCAInfo cvccainfo = (CVCCAInfo) cainfo;
            // Create CVCCA
            ca = new CVCCA(cvccainfo);
            ca.setCAToken(catoken);
        }

        // Certificate chain
        Collection<Certificate> certificatechain = null;
        String sequence = catoken.getCATokenInfo().getKeySequence(); // get from CAtoken to make sure it is fresh
        if (cainfo.getSignedBy() == CAInfo.SELFSIGNED) {
            try {
                // create selfsigned certificate
                Certificate cacertificate = null;

                log.debug("CAAdminSessionBean : " + cainfo.getSubjectDN());

                UserDataVO cadata = new UserDataVO("nobody", cainfo.getSubjectDN(), cainfo.getSubjectDN().hashCode(), caAltName, null, 0, 0, 0, cainfo
                        .getCertificateProfileId(), null, null, 0, 0, null);

                cacertificate = ca.generateCertificate(cadata, catoken.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN), -1, cainfo.getValidity(), certprofile,
                        sequence);

                log.debug("CAAdminSessionBean : " + CertTools.getSubjectDN(cacertificate));

                // Build Certificate Chain
                certificatechain = new ArrayList<Certificate>();
                certificatechain.add(cacertificate);

                // set status to active
                castatus = SecConst.CA_ACTIVE;
            } catch (CATokenOfflineException e) {
                String msg = intres.getLocalizedMessage("error.catokenoffline", cainfo.getName());
                logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CACREATED, msg, e);
                throw e;
            } catch (Exception fe) {
                String msg = intres.getLocalizedMessage("caadmin.errorcreateca", cainfo.getName());
                logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CACREATED, msg, fe);
                throw new EJBException(fe);
            }
        }
        if (cainfo.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA) {
            certificatechain = new ArrayList<Certificate>();
            // set status to waiting certificate response.
            castatus = SecConst.CA_WAITING_CERTIFICATE_RESPONSE;
        }

        if (cainfo.getSignedBy() > CAInfo.SPECIALCAIDBORDER || cainfo.getSignedBy() < 0) {
            // Create CA signed by other internal CA.
            try {
              CAData signcadata = CAData.findByIdOrThrow(entityManager, Integer.valueOf(cainfo.getSignedBy()));
                CA signca = signcadata.getCA();
                // Check that the signer is valid
                checkSignerValidity(admin, signcadata);
                // Create CA certificate
                Certificate cacertificate = null;

                UserDataVO cadata = new UserDataVO("nobody", cainfo.getSubjectDN(), cainfo.getSubjectDN().hashCode(), caAltName, null, 0, 0, 0, cainfo
                        .getCertificateProfileId(), null, null, 0, 0, null);

                cacertificate = signca.generateCertificate(cadata, catoken.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN), -1, cainfo.getValidity(), certprofile,
                        sequence);

                // Build Certificate Chain
                Collection<Certificate> rootcachain = signca.getCertificateChain();
                certificatechain = new ArrayList<Certificate>();
View Full Code Here

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

            ca.updateCA(cainfo);
            // Store CA in database
            cadata.setCA(ca);
            // Try to activate the CA token after we have edited the CA
            try {
                CATokenContainer catoken = ca.getCAToken();
                CATokenInfo catokeninfo = cainfo.getCATokenInfo();
                String authCode = catokeninfo.getAuthenticationCode();
                String keystorepass = getDefaultKeyStorePassIfSWAndEmpty(authCode, catokeninfo);
                if (keystorepass != null) {
                    catoken.activate(keystorepass);
                } else {
                    log.debug("Not trying to activate CAToken after editing, authCode == null.");
                }
            } catch (CATokenAuthenticationFailedException ctaf) {
                String msg = intres.getLocalizedMessage("caadmin.errorcreatetokenpin");
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.