List of usage examples for java.security.cert Certificate getType
public final String getType()
From source file:org.cesecore.util.CertTools.java
public static Date getNotAfter(Certificate cert) { Date ret = null;/* w w w . jav a 2s. c om*/ if (cert == null) { throw new IllegalArgumentException("getNotAfter: cert is null"); } if (cert instanceof X509Certificate) { final X509Certificate xcert = (X509Certificate) cert; ret = xcert.getNotAfter(); } else if (StringUtils.equals(cert.getType(), "CVC")) { final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; try { ret = cvccert.getCVCertificate().getCertificateBody().getValidTo(); } catch (NoSuchFieldException e) { // it is not uncommon that this field is missing in CVC certificate requests (it's not in the EAC standard so) if (log.isDebugEnabled()) { log.debug("NoSuchFieldException: " + e.getMessage()); } return null; } } return ret; }
From source file:org.cesecore.util.CertTools.java
/** * Checks that the given date is within the certificate's validity period. In other words, this determines whether the certificate would be valid * at the given date/time.//from ww w.ja v a 2 s. c o m * * This utility class is only a helper to get the same behavior as the standard java.security.cert API regardless if using X.509 or CV * Certificate. * * @param cert certificate to verify, if null the method returns immediately, null does not have a validity to check. * @param date the Date to check against to see if this certificate is valid at that date/time. * @throws NoSuchFieldException * @throws CertificateExpiredException - if the certificate has expired with respect to the date supplied. * @throws CertificateNotYetValidException - if the certificate is not yet valid with respect to the date supplied. * @see java.security.cert.X509Certificate#checkValidity(Date) */ public static void checkValidity(final Certificate cert, final Date date) throws CertificateExpiredException, CertificateNotYetValidException { if (cert != null) { if (cert instanceof X509Certificate) { final X509Certificate xcert = (X509Certificate) cert; xcert.checkValidity(date); } else if (StringUtils.equals(cert.getType(), "CVC")) { final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; try { final Date start = cvccert.getCVCertificate().getCertificateBody().getValidFrom(); final Date end = cvccert.getCVCertificate().getCertificateBody().getValidTo(); if (start.after(date)) { String msg = "Certificate startDate '" + start + "' is after check date '" + date + "'"; if (log.isTraceEnabled()) { log.trace(msg); } throw new CertificateNotYetValidException(msg); } if (end.before(date)) { final String msg = "Certificate endDate '" + end + "' is before check date '" + date + "'"; if (log.isTraceEnabled()) { log.trace(msg); } throw new CertificateExpiredException(msg); } } catch (NoSuchFieldException e) { log.error("NoSuchFieldException: ", e); } } } }
From source file:org.cesecore.util.CertTools.java
/** * Checks if a certificate is a CA certificate according to BasicConstraints (X.509), or role (CVC). If there is no basic constraints extension on * a X.509 certificate, false is returned. * /*from w ww .j ava 2 s .c o m*/ * @param cert the certificate that skall be checked. * * @return boolean true if the certificate belongs to a CA. */ public static boolean isCA(Certificate cert) { if (log.isTraceEnabled()) { log.trace(">isCA"); } boolean ret = false; if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; if (x509cert.getBasicConstraints() > -1) { ret = true; } } else if (StringUtils.equals(cert.getType(), "CVC")) { CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; try { CVCAuthorizationTemplate templ = cvccert.getCVCertificate().getCertificateBody() .getAuthorizationTemplate(); AuthorizationRole role = templ.getAuthorizationField().getAuthRole(); if (role.isCVCA() || role.isDV()) { ret = true; } } catch (NoSuchFieldException e) { log.error("NoSuchFieldException: ", e); } } if (log.isTraceEnabled()) { log.trace("<isCA:" + ret); } return ret; }
From source file:org.cesecore.util.CertTools.java
/** * Gets Serial number of the certificate as a string. For X509 Certificate this means a HEX encoded BigInteger, and for CVC certificate is means * the sequence field of the holder reference. * /*from w ww . ja v a 2 s . c om*/ * @param cert Certificate * * @return String to be displayed */ public static String getSerialNumberAsString(Certificate cert) { String ret = null; if (cert == null) { throw new IllegalArgumentException("getSerialNumber: cert is null"); } if (cert instanceof X509Certificate) { X509Certificate xcert = (X509Certificate) cert; ret = xcert.getSerialNumber().toString(16).toUpperCase(); } else if (StringUtils.equals(cert.getType(), "CVC")) { // For CVC certificates the sequence field of the HolderReference is kind of a serial number, // but if can be alphanumeric which means it can not be made into a BigInteger CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; try { ret = cvccert.getCVCertificate().getCertificateBody().getHolderReference().getSequence(); } catch (NoSuchFieldException e) { log.error("getSerialNumber: NoSuchFieldException: ", e); ret = "N/A"; } } else { throw new IllegalArgumentException( "getSerialNumber: Certificate of type " + cert.getType() + " is not implemented"); } return ret; }
From source file:org.cesecore.util.CertTools.java
/** * Dumps a certificate (cvc or x.509) to string format, suitable for manual inspection/debugging. * //from ww w. j av a 2 s . c o m * @param cert Certificate * * @return String with cvc or asn.1 dump. */ public static String dumpCertificateAsString(final Certificate cert) { String ret = null; if (cert instanceof X509Certificate) { try { final Certificate c = getCertfromByteArray(cert.getEncoded()); ret = c.toString(); // ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(cert.getEncoded())); // ASN1Primitive obj = ais.readObject(); // ret = ASN1Dump.dumpAsString(obj); } catch (CertificateException e) { ret = e.getMessage(); } } else if (StringUtils.equals(cert.getType(), "CVC")) { final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; final CVCObject obj = cvccert.getCVCertificate(); ret = obj.getAsText(""); } else { throw new IllegalArgumentException( "dumpCertificateAsString: Certificate of type " + cert.getType() + " is not implemented"); } return ret; }
From source file:org.cesecore.util.CertTools.java
/** * Gets subject or issuer DN in the format we are sure about (BouncyCastle),supporting UTF8. * /*from w ww .j a va 2s. c o m*/ * @param cert X509Certificate * @param which 1 = subjectDN, anything else = issuerDN * * @return String containing the DN. */ private static String getDN(final Certificate cert, final int which) { String ret = null; if (cert == null) { return null; } if (cert instanceof X509Certificate) { // cert.getType=X.509 try { final CertificateFactory cf = CertTools.getCertificateFactory(); final X509Certificate x509cert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(cert.getEncoded())); String dn = null; if (which == 1) { dn = x509cert.getSubjectDN().toString(); } else { dn = x509cert.getIssuerDN().toString(); } ret = stringToBCDNString(dn); } catch (CertificateException ce) { log.info("Could not get DN from X509Certificate. " + ce.getMessage()); log.debug("", ce); return null; } } else if (StringUtils.equals(cert.getType(), "CVC")) { final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; try { ReferenceField rf = null; if (which == 1) { rf = cvccert.getCVCertificate().getCertificateBody().getHolderReference(); } else { rf = cvccert.getCVCertificate().getCertificateBody().getAuthorityReference(); } if (rf != null) { // Construct a "fake" DN which can be used in EJBCA // Use only mnemonic and country, since sequence is more of a serialnumber than a DN part String dn = ""; if (rf.getMnemonic() != null) { if (StringUtils.isNotEmpty(dn)) { dn += ", "; } dn += "CN=" + rf.getMnemonic(); } if (rf.getCountry() != null) { if (StringUtils.isNotEmpty(dn)) { dn += ", "; } dn += "C=" + rf.getCountry(); } ret = stringToBCDNString(dn); } } catch (NoSuchFieldException e) { log.error("NoSuchFieldException: ", e); return null; } } return ret; }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override public void importCACertificate(AuthenticationToken admin, String caname, Collection<Certificate> certificates) throws AuthorizationDeniedException, CAExistsException, IllegalCryptoTokenException, CertificateImportException {// www . jav a 2 s.c om // Re-order if needed and validate chain if (certificates.size() != 1) { // In the case there is a chain, we require a full chain leading up to a root try { certificates = CertTools.createCertChain(certificates); } catch (CertPathValidatorException e) { throw new CertificateImportException( "The provided certificates does not form a full certificate chain."); } catch (InvalidAlgorithmParameterException e) { throw new CertificateImportException(e); } catch (NoSuchAlgorithmException e) { throw new CertificateImportException(e); } catch (NoSuchProviderException e) { throw new CertificateImportException(e); } catch (CertificateException e) { throw new CertificateImportException(e); } } final Certificate caCertificate = certificates.iterator().next(); if (!CertTools.isCA(caCertificate)) { throw new CertificateImportException("Only CA certificates can be imported using this function."); } CA ca = null; CAInfo cainfo = null; // Parameters common for both X509 and CVC CAs int certprofileid = CertTools.isSelfSigned(caCertificate) ? CertificateProfileConstants.CERTPROFILE_FIXED_ROOTCA : CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA; String subjectdn = CertTools.getSubjectDN(caCertificate); long validity = 0; int signedby = CertTools.isSelfSigned(caCertificate) ? CAInfo.SELFSIGNED : CAInfo.SIGNEDBYEXTERNALCA; log.info("Preparing to import of CA with Subject DN " + subjectdn); if (caCertificate instanceof X509Certificate) { X509Certificate x509CaCertificate = (X509Certificate) caCertificate; String subjectaltname = CertTools.getSubjectAlternativeName(x509CaCertificate); // Process certificate policies. ArrayList<CertificatePolicy> policies = new ArrayList<CertificatePolicy>(); CertificateProfile certprof = certificateProfileSession.getCertificateProfile(certprofileid); if (certprof.getCertificatePolicies() != null && certprof.getCertificatePolicies().size() > 0) { policies.addAll(certprof.getCertificatePolicies()); } X509CAInfo x509cainfo = new X509CAInfo(subjectdn, caname, CAConstants.CA_EXTERNAL, certprofileid, validity, signedby, null, null); x509cainfo.setSubjectAltName(subjectaltname); x509cainfo.setPolicies(policies); x509cainfo.setExpireTime(CertTools.getNotAfter(x509CaCertificate)); cainfo = x509cainfo; } else if (StringUtils.equals(caCertificate.getType(), "CVC")) { cainfo = new CVCCAInfo(subjectdn, caname, CAConstants.CA_EXTERNAL, certprofileid, validity, signedby, null, null); } cainfo.setDescription("CA created by certificate import."); if (cainfo instanceof X509CAInfo) { log.info("Creating a X509 CA (process request)"); ca = new X509CA((X509CAInfo) cainfo); } else if (cainfo instanceof CVCCAInfo) { // CVC CA is a special type of CA for EAC electronic passports log.info("Creating a CVC CA (process request)"); CVCCAInfo cvccainfo = (CVCCAInfo) cainfo; ca = CvcCA.getInstance(cvccainfo); } ca.setCertificateChain(certificates); CAToken token = new CAToken(ca.getCAId(), new NullCryptoToken().getProperties()); try { ca.setCAToken(token); } catch (InvalidAlgorithmException e) { throw new IllegalCryptoTokenException(e); } // Add CA caSession.addCA(admin, ca); // Publish CA certificates. publishCACertificate(admin, certificates, null, ca.getSubjectDN()); }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override public void receiveResponse(AuthenticationToken authenticationToken, int caid, ResponseMessage responsemessage, Collection<?> cachain, String nextKeyAlias) throws AuthorizationDeniedException, CertPathValidatorException, EjbcaException, CesecoreException { if (log.isTraceEnabled()) { log.trace(">receiveResponse: " + caid); }/* w w w . j ava 2s .c o m*/ if (!accessSession.isAuthorizedNoLogging(authenticationToken, AccessRulesConstants.REGULAR_RENEWCA)) { final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtocertresp", Integer.valueOf(caid)); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg); } try { final CA ca = caSession.getCAForEdit(authenticationToken, caid); if (!(responsemessage instanceof X509ResponseMessage)) { String msg = intres.getLocalizedMessage("caadmin.errorcertrespillegalmsg", responsemessage != null ? responsemessage.getClass().getName() : "null"); log.info(msg); throw new EjbcaException(msg); } final Certificate cacert = ((X509ResponseMessage) responsemessage).getCertificate(); // Receiving a certificate for an internal CA will transform it into an externally signed CA if (ca.getSignedBy() != CAInfo.SIGNEDBYEXTERNALCA) { ca.setSignedBy(CAInfo.SIGNEDBYEXTERNALCA); } // Check that CA DN is equal to the certificate response. if (!CertTools.getSubjectDN(cacert).equals(CertTools.stringToBCDNString(ca.getSubjectDN()))) { String msg = intres.getLocalizedMessage("caadmin.errorcertrespwrongdn", CertTools.getSubjectDN(cacert), ca.getSubjectDN()); log.info(msg); throw new EjbcaException(msg); } List<Certificate> tmpchain = new ArrayList<Certificate>(); tmpchain.add(cacert); Collection<Certificate> reqchain = null; if (cachain != null && cachain.size() > 0) { // 1. If we have a chain given as parameter, we will use that. reqchain = CertTools.createCertChain(cachain); log.debug("Using CA certificate chain from parameter of size: " + reqchain.size()); } else { // 2. If no parameter is given we assume that the request chain was stored when the request was created. reqchain = ca.getRequestCertificateChain(); if (reqchain == null) { // 3. Lastly, if that failed we'll check if the certificate chain in it's entirety already exists in the database. reqchain = new ArrayList<Certificate>(); Certificate issuer = certificateStoreSession .findLatestX509CertificateBySubject(CertTools.getIssuerDN(cacert)); if (issuer != null) { reqchain.add(issuer); while (!CertTools.isSelfSigned(issuer)) { issuer = certificateStoreSession .findLatestX509CertificateBySubject(CertTools.getIssuerDN(issuer)); if (issuer != null) { reqchain.add(issuer); } else { String msg = intres.getLocalizedMessage("caadmin.errorincompleterequestchain", caid, ca.getSubjectDN()); log.info(msg); throw new CertPathValidatorException(msg); } } } if (reqchain.size() == 0) { String msg = intres.getLocalizedMessage("caadmin.errornorequestchain", caid, ca.getSubjectDN()); log.info(msg); throw new CertPathValidatorException(msg); } } else { if (log.isDebugEnabled()) { log.debug("Using pre-stored CA certificate chain."); } } } log.debug("Picked up request certificate chain of size: " + reqchain.size()); tmpchain.addAll(reqchain); final List<Certificate> chain = CertTools.createCertChain(tmpchain); log.debug("Storing certificate chain of size: " + chain.size()); // Before importing the certificate we want to make sure that the public key matches the CAs private key PublicKey caCertPublicKey = cacert.getPublicKey(); // If it is a DV certificate signed by a CVCA, enrich the public key for EC parameters from the CVCA's certificate if (StringUtils.equals(cacert.getType(), "CVC")) { if (caCertPublicKey.getAlgorithm().equals("ECDSA")) { CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cacert; try { if (cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate() .getAuthorizationField().getAuthRole().isDV()) { log.debug("Enriching DV public key with EC parameters from CVCA"); Certificate cvcacert = (Certificate) reqchain.iterator().next(); caCertPublicKey = KeyTools.getECPublicKeyWithParams(caCertPublicKey, cvcacert.getPublicKey()); } } catch (InvalidKeySpecException e) { log.debug("Strange CVCA certificate that we can't get the key from, continuing anyway...", e); } catch (NoSuchFieldException e) { log.debug("Strange DV certificate with no AutheorizationRole, continuing anyway...", e); } } else { log.debug("Key is not ECDSA, don't try to enrich with EC parameters."); } } else { log.debug("Cert is not CVC, no need to enrich with EC parameters."); } final CAToken catoken = ca.getCAToken(); final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(catoken.getCryptoTokenId()); boolean activatedNextSignKey = false; if (nextKeyAlias != null) { try { if (log.isDebugEnabled()) { log.debug("SubjectKeyId for CA cert public key: " + new String( Hex.encode(KeyTools.createSubjectKeyId(caCertPublicKey).getKeyIdentifier()))); log.debug("SubjectKeyId for CA next public key: " + new String(Hex.encode(KeyTools .createSubjectKeyId(cryptoToken.getPublicKey(nextKeyAlias)).getKeyIdentifier()))); } KeyTools.testKey(cryptoToken.getPrivateKey(nextKeyAlias), caCertPublicKey, cryptoToken.getSignProviderName()); } catch (InvalidKeyException e) { throw new EjbcaException(ErrorCode.INVALID_KEY, e); } catoken.setNextCertSignKey(nextKeyAlias); catoken.activateNextSignKey(); activatedNextSignKey = true; } else { // Since we don't specified the nextSignKey, we will just try the current or next CA sign key try { KeyTools.testKey( cryptoToken.getPrivateKey( catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)), caCertPublicKey, cryptoToken.getSignProviderName()); } catch (Exception e1) { log.debug( "The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN, trying CAKEYPURPOSE_CERTSIGN_NEXT..."); if (e1 instanceof InvalidKeyException) { log.trace(e1); } else { // If it's not invalid key, we want to see more of the error log.debug("Error: ", e1); } try { KeyTools.testKey( cryptoToken.getPrivateKey( catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN_NEXT)), caCertPublicKey, cryptoToken.getSignProviderName()); // This was OK, so we must also activate the next signing key when importing this certificate catoken.activateNextSignKey(); activatedNextSignKey = true; } catch (Exception e2) { log.debug( "The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN_NEXT either, giving up."); if ((e2 instanceof InvalidKeyException) || (e2 instanceof IllegalArgumentException)) { log.trace(e2); } else { // If it's not invalid key or missing authentication code, we want to see more of the error log.debug("Error: ", e2); } throw new EjbcaException(ErrorCode.INVALID_KEY, e2); } } } if (activatedNextSignKey) { // Activated the next signing key(s) so generate audit log final Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", intres.getLocalizedMessage("catoken.activatednextkey", caid)); details.put("certSignKey", catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); details.put("crlSignKey", catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN)); details.put("sequence", catoken.getKeySequence()); auditSession.log(EventTypes.CA_KEYACTIVATE, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, details); } ca.setCAToken(catoken); ca.setCertificateChain(chain); // Set status to active, so we can sign certificates for the external services below. ca.setStatus(CAConstants.CA_ACTIVE); // activate External CA Services for (int type : ca.getExternalCAServiceTypes()) { try { ca.initExtendedService(cryptoToken, type, ca); final ExtendedCAServiceInfo info = ca.getExtendedCAServiceInfo(type); if (info instanceof BaseSigningCAServiceInfo) { // Publish the extended service certificate, but only for active services if (info.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE) { final List<Certificate> extcacertificate = new ArrayList<Certificate>(); extcacertificate.add(((BaseSigningCAServiceInfo) info).getCertificatePath().get(0)); publishCACertificate(authenticationToken, extcacertificate, ca.getCRLPublishers(), ca.getSubjectDN()); } } } catch (Exception fe) { final String detailsMsg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", Integer.valueOf(caid)); auditSession.log(EventTypes.CA_EDITING, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg); throw new EJBException(fe); } } // Set expire time ca.setExpireTime(CertTools.getNotAfter(cacert)); // Save CA caSession.editCA(authenticationToken, ca, true); // Publish CA Certificate publishCACertificate(authenticationToken, chain, ca.getCRLPublishers(), ca.getSubjectDN()); // Create initial CRL publishingCrlSession.forceCRL(authenticationToken, caid); publishingCrlSession.forceDeltaCRL(authenticationToken, caid); // All OK String detailsMsg = intres.getLocalizedMessage("caadmin.certrespreceived", Integer.valueOf(caid)); auditSession.log(EventTypes.CA_EDITING, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg); } catch (CryptoTokenOfflineException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (CADoesntExistsException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (CertificateEncodingException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } catch (CertificateException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } catch (InvalidAlgorithmParameterException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } catch (NoSuchAlgorithmException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } catch (NoSuchProviderException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } if (log.isTraceEnabled()) { log.trace("<receiveResponse: " + caid); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
/** * @param keyAlgorithm keyalgorithm for extended CA services, OCSP, XKMS, CMS. Example AlgorithmConstants.KEYALGORITHM_RSA * @param keySpecification keyspecification for extended CA services, OCSP, XKMS, CMS. Example 2048 * @throws AuthorizationDeniedException if imported CA was signed by a CA user does not have authorization to. * @throws CADoesntExistsException if superCA does not exist * @throws CAExistsException if the CA already exists * @throws CAOfflineException if CRLs can not be generated because imported CA did not manage to get online * @throws CryptoTokenAuthenticationFailedException if authentication to crypto token failed * @throws IllegalCryptoTokenException if CA certificate was not self signed, and chain length > 1 * @throws CryptoTokenOfflineException if crypto token is unavailable. * // www.ja v a2 s. c o m */ private CA importCA(AuthenticationToken admin, String caname, String keystorepass, Certificate[] signatureCertChain, CAToken catoken, String keyAlgorithm, String keySpecification) throws CryptoTokenAuthenticationFailedException, CryptoTokenOfflineException, IllegalCryptoTokenException, AuthorizationDeniedException, CAExistsException, CAOfflineException { // Create a new CA int signedby = CAInfo.SIGNEDBYEXTERNALCA; int certprof = CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA; String description = "Imported external signed CA"; Certificate caSignatureCertificate = signatureCertChain[0]; ArrayList<Certificate> certificatechain = new ArrayList<Certificate>(); for (int i = 0; i < signatureCertChain.length; i++) { certificatechain.add(signatureCertChain[i]); } if (signatureCertChain.length == 1) { if (verifyIssuer(caSignatureCertificate, caSignatureCertificate)) { signedby = CAInfo.SELFSIGNED; certprof = CertificateProfileConstants.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 " + CertTools.getSubjectDN(caSignatureCertificate) + ": certificate " + CertTools.getSerialNumberAsString(caSignatureCertificate) + " is not self-signed."); throw new IllegalCryptoTokenException( "Cannot import CA " + CertTools.getSubjectDN(caSignatureCertificate) + ": certificate is not self-signed. Check " + "certificate chain in PKCS#12"); } } else if (signatureCertChain.length > 1) { // 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. for (int caid : caSession.getAllCaIds()) { CAInfo superCaInfo; try { superCaInfo = caSession.getCAInfo(admin, caid); } catch (CADoesntExistsException e) { throw new IllegalStateException( "Newly retrieved CA " + caid + " does not exist in the system."); } Iterator<Certificate> i = superCaInfo.getCertificateChain().iterator(); if (i.hasNext()) { Certificate superCaCert = i.next(); if (verifyIssuer(caSignatureCertificate, superCaCert)) { signedby = caid; description = "Imported sub CA"; break; } } } } CAInfo cainfo = null; CA ca = null; int validity = (int) ((CertTools.getNotAfter(caSignatureCertificate).getTime() - CertTools.getNotBefore(caSignatureCertificate).getTime()) / (24 * 3600 * 1000)); ArrayList<ExtendedCAServiceInfo> extendedcaservices = new ArrayList<ExtendedCAServiceInfo>(); ArrayList<Integer> approvalsettings = new ArrayList<Integer>(); ArrayList<Integer> crlpublishers = new ArrayList<Integer>(); if (caSignatureCertificate instanceof X509Certificate) { // Create an X509CA // Create and active extended CA Services (XKMS, CMS). // Create and active XKMS CA Service. extendedcaservices.add(new XKMSCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE, "CN=XKMSCertificate, " + CertTools.getSubjectDN(caSignatureCertificate), "", keySpecification, keyAlgorithm)); // Create and active CMS CA Service. extendedcaservices.add(new CmsCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE, "CN=CMSCertificate, " + CertTools.getSubjectDN(caSignatureCertificate), "", keySpecification, keyAlgorithm)); cainfo = new X509CAInfo(CertTools.getSubjectDN(caSignatureCertificate), caname, CAConstants.CA_ACTIVE, certprof, validity, signedby, certificatechain, catoken); cainfo.setExpireTime(CertTools.getNotAfter(caSignatureCertificate)); cainfo.setDescription(description); cainfo.setCRLPublishers(crlpublishers); cainfo.setExtendedCAServiceInfos(extendedcaservices); cainfo.setApprovalSettings(approvalsettings); ca = new X509CA((X509CAInfo) cainfo); } else if (caSignatureCertificate.getType().equals("CVC")) { // Create a CVC CA // Create the CAInfo to be used for either generating the whole CA // or making a request cainfo = new CVCCAInfo(CertTools.getSubjectDN(caSignatureCertificate), caname, CAConstants.CA_ACTIVE, certprof, validity, signedby, certificatechain, catoken); cainfo.setExpireTime(CertTools.getNotAfter(caSignatureCertificate)); cainfo.setDescription(description); cainfo.setCRLPublishers(crlpublishers); cainfo.setExtendedCAServiceInfos(extendedcaservices); cainfo.setApprovalSettings(approvalsettings); ca = CvcCA.getInstance((CVCCAInfo) cainfo); } // We must activate the token, in case it does not have the default password final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(catoken.getCryptoTokenId()); cryptoToken.activate(keystorepass.toCharArray()); try { ca.setCAToken(catoken); } catch (InvalidAlgorithmException e) { throw new IllegalCryptoTokenException(e); } ca.setCertificateChain(certificatechain); log.debug("CA-Info: " + catoken.getSignatureAlgorithm() + " " + ca.getCAToken().getEncryptionAlgorithm()); // Publish CA certificates. publishCACertificate(admin, ca.getCertificateChain(), ca.getCRLPublishers(), ca.getSubjectDN()); // activate External CA Services activateAndPublishExternalCAServices(admin, cainfo.getExtendedCAServiceInfos(), ca); // Store CA in database. caSession.addCA(admin, ca); // Create initial CRLs try { publishingCrlSession.forceCRL(admin, ca.getCAId()); publishingCrlSession.forceDeltaCRL(admin, ca.getCAId()); } catch (CADoesntExistsException e) { throw new IllegalStateException( "Newly created CA with ID: " + ca.getCAId() + " was not found in database."); } return ca; }