List of usage examples for java.security.cert X509Certificate getIssuerX500Principal
public X500Principal getIssuerX500Principal()
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Create a Truststore alias that would be used for adding the given trusted * X509 certificate to the Truststore. The alias is cretaed as * "trustedcert#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"< * CERT_SERIAL_NUMBER>//from w ww . ja va 2s. c o m * * @param cert * certificate to generate the alias for * @return the alias for the given certificate */ @Override public String createTrustedCertificateAlias(X509Certificate cert) { String ownerDN = cert.getSubjectX500Principal().getName(RFC2253); ParsedDistinguishedName parsedDN = dnParser.parseDN(ownerDN); String owner; String ownerCN = parsedDN.getCN(); // owner's common name String ownerOU = parsedDN.getOU(); String ownerO = parsedDN.getO(); if (!ownerCN.equals("none")) { // try owner's CN first owner = ownerCN; } // try owner's OU else if (!ownerOU.equals("none")) { owner = ownerOU; } else if (!ownerO.equals("none")) { // finally use owner's Organisation owner = ownerO; } else { owner = "<Not Part of Certificate>"; } /* Get the hexadecimal representation of the certificate's serial number */ String serialNumber = new BigInteger(1, cert.getSerialNumber().toByteArray()).toString(16).toUpperCase(); String issuerDN = cert.getIssuerX500Principal().getName(RFC2253); parsedDN = dnParser.parseDN(issuerDN); String issuer; String issuerCN = parsedDN.getCN(); // issuer's common name String issuerOU = parsedDN.getOU(); String issuerO = parsedDN.getO(); if (!issuerCN.equals("none")) { // try issuer's CN first issuer = issuerCN; } // try issuer's OU else if (!issuerOU.equals("none")) { issuer = issuerOU; } else if (!issuerO.equals("none")) { // finally use issuer's // Organisation issuer = issuerO; } else { issuer = "<Not Part of Certificate>"; } String alias = "trustedcert#" + owner + "#" + issuer + "#" + serialNumber; return alias; }
From source file:be.fedict.eid.tsl.TrustServiceList.java
private void xmlSign(PrivateKey privateKey, X509Certificate certificate, String tslId) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException {//from w ww . j a v a 2 s.c o m XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI()); LOG.debug("xml signature factory: " + signatureFactory.getClass().getName()); LOG.debug("loader: " + signatureFactory.getClass().getClassLoader()); XMLSignContext signContext = new DOMSignContext(privateKey, this.tslDocument.getDocumentElement()); signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA256, null); List<Reference> references = new LinkedList<Reference>(); List<Transform> transforms = new LinkedList<Transform>(); transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("#" + tslId, digestMethod, transforms, null, null); references.add(reference); String signatureId = "xmldsig-" + UUID.randomUUID().toString(); List<XMLObject> objects = new LinkedList<XMLObject>(); addXadesBes(signatureFactory, this.tslDocument, signatureId, certificate, references, objects); SignatureMethod signatureMethod; if (isJava6u18OrAbove()) { signatureMethod = signatureFactory .newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null); } else { signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); } CanonicalizationMethod canonicalizationMethod = signatureFactory .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references); List<Object> keyInfoContent = new LinkedList<Object>(); KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance(); List<Object> x509DataObjects = new LinkedList<Object>(); x509DataObjects.add(certificate); x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(certificate.getIssuerX500Principal().toString(), certificate.getSerialNumber())); X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects); keyInfoContent.add(x509Data); KeyValue keyValue; try { keyValue = keyInfoFactory.newKeyValue(certificate.getPublicKey()); } catch (KeyException e) { throw new RuntimeException("key exception: " + e.getMessage(), e); } keyInfoContent.add(keyValue); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent); String signatureValueId = signatureId + "-signature-value"; XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo, objects, signatureId, signatureValueId); xmlSignature.sign(signContext); }
From source file:be.fedict.eid.dss.ws.DSSUtil.java
/** * Adds a DSS Verification Report to specified optional output element from * the specified list of {@link SignatureInfo}'s * // w ww . jav a 2 s. co m * @param optionalOutput * optional output to add verification report to * @param signatureInfos * signature infos to use in verification report. */ public static void addVerificationReport(AnyType optionalOutput, List<SignatureInfo> signatureInfos) { LOG.debug("return verification report"); VerificationReportType verificationReport = vrObjectFactory.createVerificationReportType(); List<IndividualReportType> individualReports = verificationReport.getIndividualReport(); for (SignatureInfo signatureInfo : signatureInfos) { X509Certificate signerCertificate = signatureInfo.getSigner(); IndividualReportType individualReport = vrObjectFactory.createIndividualReportType(); individualReports.add(individualReport); SignedObjectIdentifierType signedObjectIdentifier = vrObjectFactory.createSignedObjectIdentifierType(); individualReport.setSignedObjectIdentifier(signedObjectIdentifier); SignedPropertiesType signedProperties = vrObjectFactory.createSignedPropertiesType(); signedObjectIdentifier.setSignedProperties(signedProperties); SignedSignaturePropertiesType signedSignatureProperties = vrObjectFactory .createSignedSignaturePropertiesType(); signedProperties.setSignedSignatureProperties(signedSignatureProperties); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(signatureInfo.getSigningTime()); signedSignatureProperties.setSigningTime(datatypeFactory.newXMLGregorianCalendar(calendar)); be.fedict.eid.dss.ws.profile.vr.jaxb.dss.Result individualResult = vrDssObjectFactory.createResult(); individualReport.setResult(individualResult); individualResult.setResultMajor(DSSConstants.RESULT_MAJOR_SUCCESS); individualResult.setResultMinor(DSSConstants.RESULT_MINOR_VALID_SIGNATURE); be.fedict.eid.dss.ws.profile.vr.jaxb.dss.AnyType details = vrDssObjectFactory.createAnyType(); individualReport.setDetails(details); DetailedSignatureReportType detailedSignatureReport = vrObjectFactory .createDetailedSignatureReportType(); details.getAny().add(vrObjectFactory.createDetailedSignatureReport(detailedSignatureReport)); VerificationResultType formatOKVerificationResult = vrObjectFactory.createVerificationResultType(); formatOKVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); detailedSignatureReport.setFormatOK(formatOKVerificationResult); SignatureValidityType signatureOkSignatureValidity = vrObjectFactory.createSignatureValidityType(); detailedSignatureReport.setSignatureOK(signatureOkSignatureValidity); VerificationResultType sigMathOkVerificationResult = vrObjectFactory.createVerificationResultType(); signatureOkSignatureValidity.setSigMathOK(sigMathOkVerificationResult); sigMathOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); if (null != signatureInfo.getRole()) { PropertiesType properties = vrObjectFactory.createPropertiesType(); detailedSignatureReport.setProperties(properties); SignedPropertiesType vrSignedProperties = vrObjectFactory.createSignedPropertiesType(); properties.setSignedProperties(vrSignedProperties); SignedSignaturePropertiesType vrSignedSignatureProperties = vrObjectFactory .createSignedSignaturePropertiesType(); vrSignedProperties.setSignedSignatureProperties(vrSignedSignatureProperties); vrSignedSignatureProperties.setSigningTime(datatypeFactory.newXMLGregorianCalendar(calendar)); SignerRoleType signerRole = vrObjectFactory.createSignerRoleType(); vrSignedSignatureProperties.setSignerRole(signerRole); ClaimedRolesListType claimedRolesList = vrXadesObjectFactory.createClaimedRolesListType(); signerRole.setClaimedRoles(claimedRolesList); be.fedict.eid.dss.ws.profile.vr.jaxb.xades.AnyType claimedRoleAny = vrXadesObjectFactory .createAnyType(); claimedRolesList.getClaimedRole().add(claimedRoleAny); claimedRoleAny.getContent().add(signatureInfo.getRole()); } CertificatePathValidityType certificatePathValidity = vrObjectFactory .createCertificatePathValidityType(); detailedSignatureReport.setCertificatePathValidity(certificatePathValidity); VerificationResultType certPathVerificationResult = vrObjectFactory.createVerificationResultType(); certPathVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); certificatePathValidity.setPathValiditySummary(certPathVerificationResult); X509IssuerSerialType certificateIdentifier = vrXmldsigObjectFactory.createX509IssuerSerialType(); certificatePathValidity.setCertificateIdentifier(certificateIdentifier); certificateIdentifier.setX509IssuerName(signerCertificate.getIssuerX500Principal().toString()); certificateIdentifier.setX509SerialNumber(signerCertificate.getSerialNumber()); CertificatePathValidityVerificationDetailType certificatePathValidityVerificationDetail = vrObjectFactory .createCertificatePathValidityVerificationDetailType(); certificatePathValidity.setPathValidityDetail(certificatePathValidityVerificationDetail); CertificateValidityType certificateValidity = vrObjectFactory.createCertificateValidityType(); certificatePathValidityVerificationDetail.getCertificateValidity().add(certificateValidity); certificateValidity.setCertificateIdentifier(certificateIdentifier); certificateValidity.setSubject(signerCertificate.getSubjectX500Principal().toString()); VerificationResultType chainingOkVerificationResult = vrObjectFactory.createVerificationResultType(); certificateValidity.setChainingOK(chainingOkVerificationResult); chainingOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); VerificationResultType validityPeriodOkVerificationResult = vrObjectFactory .createVerificationResultType(); certificateValidity.setValidityPeriodOK(validityPeriodOkVerificationResult); validityPeriodOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); VerificationResultType extensionsOkVerificationResult = vrObjectFactory.createVerificationResultType(); certificateValidity.setExtensionsOK(extensionsOkVerificationResult); extensionsOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); try { certificateValidity.setCertificateValue(signerCertificate.getEncoded()); } catch (CertificateEncodingException e) { throw new RuntimeException("X509 encoding error: " + e.getMessage(), e); } certificateValidity.setSignatureOK(signatureOkSignatureValidity); CertificateStatusType certificateStatus = vrObjectFactory.createCertificateStatusType(); certificateValidity.setCertificateStatus(certificateStatus); VerificationResultType certStatusOkVerificationResult = vrObjectFactory.createVerificationResultType(); certificateStatus.setCertStatusOK(certStatusOkVerificationResult); certStatusOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); } Document newDocument = documentBuilder.newDocument(); Element newElement = newDocument.createElement("newNode"); try { vrMarshaller.marshal(vrObjectFactory.createVerificationReport(verificationReport), newElement); } catch (JAXBException e) { throw new RuntimeException("JAXB error: " + e.getMessage(), e); } Element verificationReportElement = (Element) newElement.getFirstChild(); optionalOutput.getAny().add(verificationReportElement); }
From source file:com.iiordanov.bVNC.RemoteCanvas.java
/** * If there is a saved cert, checks the one given against it. If a signature was passed in * and no saved cert, then check that signature. Otherwise, presents the * given cert's signature to the user for approval. * /*from w ww .ja v a 2 s .com*/ * The saved data must always win over any passed-in URI data * * @param cert the given cert. */ private void validateX509Cert(final X509Certificate cert) { boolean certMismatch = false; int hashAlg = connection.getIdHashAlgorithm(); byte[] certData = null; boolean isSigEqual = false; try { certData = cert.getEncoded(); isSigEqual = SecureTunnel.isSignatureEqual(hashAlg, connection.getIdHash(), certData); } catch (Exception ex) { ex.printStackTrace(); showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature)); return; } // If there is no saved cert, then if a signature was provided, // check the signature and save the cert if the signature matches. if (connection.getSshHostKey().equals("")) { if (!connection.getIdHash().equals("")) { if (isSigEqual) { Log.i(TAG, "Certificate validated from URI data."); saveAndAcceptCert(cert); return; } else { certMismatch = true; } } // If there is a saved cert, check against it. } else if (connection.getSshHostKey().equals(Base64.encodeToString(certData, Base64.DEFAULT))) { Log.i(TAG, "Certificate validated from saved key."); saveAndAcceptCert(cert); return; } else { certMismatch = true; } // Show a dialog with the key signature for approval. DialogInterface.OnClickListener signatureNo = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // We were told not to continue, so stop the activity Log.i(TAG, "Certificate rejected by user."); closeConnection(); ((Activity) getContext()).finish(); } }; DialogInterface.OnClickListener signatureYes = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.i(TAG, "Certificate accepted by user."); saveAndAcceptCert(cert); } }; // Display dialog to user with cert info and hash. try { // First build the message. If there was a mismatch, prepend a warning about it. String message = ""; if (certMismatch) { message = getContext().getString(R.string.warning_cert_does_not_match) + "\n\n"; } byte[] certBytes = cert.getEncoded(); String certIdHash = SecureTunnel.computeSignatureByAlgorithm(hashAlg, certBytes); String certInfo = String.format(Locale.US, getContext().getString(R.string.info_cert_tunnel), certIdHash, cert.getSubjectX500Principal().getName(), cert.getIssuerX500Principal().getName(), cert.getNotBefore(), cert.getNotAfter()); certInfo = message + certInfo.replace(",", "\n"); // Actually display the message Utils.showYesNoPrompt(getContext(), getContext().getString(R.string.info_continue_connecting) + connection.getAddress() + "?", certInfo, signatureYes, signatureNo); } catch (NoSuchAlgorithmException e2) { e2.printStackTrace(); showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature)); } catch (CertificateEncodingException e) { e.printStackTrace(); showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_encoding)); } }
From source file:org.cesecore.certificates.ca.X509CA.java
/** * Sequence is ignored by X509CA. The ctParams argument will NOT be kept after the function call returns, * and is allowed to contain references to session beans. * /* ww w.j a v a2 s . co m*/ * @throws CAOfflineException if the CA wasn't active * @throws InvalidAlgorithmException if the signing algorithm in the certificate profile (or the CA Token if not found) was invalid. * @throws IllegalValidityException if validity was invalid * @throws IllegalNameException if the name specified in the certificate request was invalid * @throws CertificateExtensionException if any of the certificate extensions were invalid * @throws OperatorCreationException if CA's private key contained an unknown algorithm or provider * @throws CertificateCreateException if an error occurred when trying to create a certificate. * @throws SignatureException if the CA's certificate's and request's certificate's and signature algorithms differ */ private Certificate generateCertificate(final EndEntityInformation subject, final RequestMessage request, final PublicKey publicKey, final int keyusage, final Date notBefore, final Date notAfter, final CertificateProfile certProfile, final Extensions extensions, final String sequence, final PublicKey caPublicKey, final PrivateKey caPrivateKey, final String provider, CertificateGenerationParams certGenParams) throws CAOfflineException, InvalidAlgorithmException, IllegalValidityException, IllegalNameException, CertificateExtensionException, OperatorCreationException, CertificateCreateException, SignatureException { // We must only allow signing to take place if the CA itself is on line, even if the token is on-line. // We have to allow expired as well though, so we can renew expired CAs if ((getStatus() != CAConstants.CA_ACTIVE) && ((getStatus() != CAConstants.CA_EXPIRED))) { final String msg = intres.getLocalizedMessage("error.caoffline", getName(), getStatus()); if (log.isDebugEnabled()) { log.debug(msg); // This is something we handle so no need to log with higher priority } throw new CAOfflineException(msg); } final String sigAlg; if (certProfile.getSignatureAlgorithm() == null) { sigAlg = getCAToken().getSignatureAlgorithm(); } else { sigAlg = certProfile.getSignatureAlgorithm(); } // Check that the signature algorithm is one of the allowed ones if (!ArrayUtils.contains(AlgorithmConstants.AVAILABLE_SIGALGS, sigAlg)) { final String msg = intres.getLocalizedMessage("createcert.invalidsignaturealg", sigAlg); throw new InvalidAlgorithmException(msg); } // Check if this is a root CA we are creating final boolean isRootCA = certProfile.getType() == CertificateConstants.CERTTYPE_ROOTCA; final X509Certificate cacert = (X509Certificate) getCACertificate(); // Check CA certificate PrivateKeyUsagePeriod if it exists (throws CAOfflineException if it exists and is not within this time) CertificateValidity.checkPrivateKeyUsagePeriod(cacert); // Get certificate validity time notBefore and notAfter final CertificateValidity val = new CertificateValidity(subject, certProfile, notBefore, notAfter, cacert, isRootCA); final BigInteger serno; { // Serialnumber is either random bits, where random generator is initialized by the serno generator. // Or a custom serial number defined in the end entity object final ExtendedInformation ei = subject.getExtendedinformation(); if (certProfile.getAllowCertSerialNumberOverride()) { if (ei != null && ei.certificateSerialNumber() != null) { serno = ei.certificateSerialNumber(); } else { serno = SernoGeneratorRandom.instance().getSerno(); } } else { serno = SernoGeneratorRandom.instance().getSerno(); if ((ei != null) && (ei.certificateSerialNumber() != null)) { final String msg = intres.getLocalizedMessage( "createcert.certprof_not_allowing_cert_sn_override_using_normal", ei.certificateSerialNumber().toString(16)); log.info(msg); } } } // Make DNs String dn = subject.getCertificateDN(); if (certProfile.getUseSubjectDNSubSet()) { dn = certProfile.createSubjectDNSubSet(dn); } final X500NameStyle nameStyle; if (getUsePrintableStringSubjectDN()) { nameStyle = PrintableStringNameStyle.INSTANCE; } else { nameStyle = CeSecoreNameStyle.INSTANCE; } if (certProfile.getUseCNPostfix()) { dn = CertTools.insertCNPostfix(dn, certProfile.getCNPostfix(), nameStyle); } // Will we use LDAP DN order (CN first) or X500 DN order (CN last) for the subject DN final boolean ldapdnorder; if ((getUseLdapDNOrder() == false) || (certProfile.getUseLdapDnOrder() == false)) { ldapdnorder = false; } else { ldapdnorder = true; } final X500Name subjectDNName; if (certProfile.getAllowDNOverride() && (request != null) && (request.getRequestX500Name() != null)) { subjectDNName = request.getRequestX500Name(); if (log.isDebugEnabled()) { log.debug("Using X509Name from request instead of user's registered."); } } else { final ExtendedInformation ei = subject.getExtendedinformation(); if (certProfile.getAllowDNOverrideByEndEntityInformation() && ei != null && ei.getRawSubjectDn() != null) { final String stripped = StringTools.strip(ei.getRawSubjectDn()); final String escapedPluses = CertTools.handleUnescapedPlus(stripped); final String emptiesRemoved = DNFieldsUtil.removeAllEmpties(escapedPluses); final X500Name subjectDNNameFromEei = CertTools.stringToUnorderedX500Name(emptiesRemoved, CeSecoreNameStyle.INSTANCE); if (subjectDNNameFromEei.toString().length() > 0) { subjectDNName = subjectDNNameFromEei; if (log.isDebugEnabled()) { log.debug( "Using X500Name from end entity information instead of user's registered subject DN fields."); log.debug("ExtendedInformation.getRawSubjectDn(): " + ei.getRawSubjectDn() + " will use: " + CeSecoreNameStyle.INSTANCE.toString(subjectDNName)); } } else { subjectDNName = CertTools.stringToBcX500Name(dn, nameStyle, ldapdnorder); } } else { subjectDNName = CertTools.stringToBcX500Name(dn, nameStyle, ldapdnorder); } } // Make sure the DN does not contain dangerous characters if (StringTools.hasStripChars(subjectDNName.toString())) { if (log.isTraceEnabled()) { log.trace("DN with illegal name: " + subjectDNName); } final String msg = intres.getLocalizedMessage("createcert.illegalname"); throw new IllegalNameException(msg); } if (log.isDebugEnabled()) { log.debug("Using subjectDN: " + subjectDNName.toString()); } // We must take the issuer DN directly from the CA-certificate otherwise we risk re-ordering the DN // which many applications do not like. X500Name issuerDNName; if (isRootCA) { // This will be an initial root CA, since no CA-certificate exists // Or it is a root CA, since the cert is self signed. If it is a root CA we want to use the same encoding for subject and issuer, // it might have changed over the years. if (log.isDebugEnabled()) { log.debug("Using subject DN also as issuer DN, because it is a root CA"); } issuerDNName = subjectDNName; } else { issuerDNName = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded()); if (log.isDebugEnabled()) { log.debug("Using issuer DN directly from the CA certificate: " + issuerDNName.toString()); } } SubjectPublicKeyInfo pkinfo; try { pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); } catch (IOException e) { throw new IllegalStateException("Caught unexpected IOException.", e); } final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(issuerDNName, serno, val.getNotBefore(), val.getNotAfter(), subjectDNName, pkinfo); // Only created and used if Certificate Transparency is enabled final X509v3CertificateBuilder precertbuilder = certProfile.isUseCertificateTransparencyInCerts() ? new X509v3CertificateBuilder(issuerDNName, serno, val.getNotBefore(), val.getNotAfter(), subjectDNName, pkinfo) : null; // Check that the certificate fulfills name constraints if (cacert instanceof X509Certificate) { GeneralNames altNameGNs = null; String altName = subject.getSubjectAltName(); if (certProfile.getUseSubjectAltNameSubSet()) { altName = certProfile.createSubjectAltNameSubSet(altName); } if (altName != null && altName.length() > 0) { altNameGNs = CertTools.getGeneralNamesFromAltName(altName); } CertTools.checkNameConstraints((X509Certificate) cacert, subjectDNName, altNameGNs); } // If the subject has Name Constraints, then name constraints must be enabled in the certificate profile! if (subject.getExtendedinformation() != null) { final ExtendedInformation ei = subject.getExtendedinformation(); final List<String> permittedNC = ei.getNameConstraintsPermitted(); final List<String> excludedNC = ei.getNameConstraintsExcluded(); if ((permittedNC != null && !permittedNC.isEmpty()) || (excludedNC != null && !excludedNC.isEmpty())) { if (!certProfile.getUseNameConstraints()) { throw new CertificateCreateException( "Tried to issue a certificate with Name Constraints without having enabled NC in the certificate profile."); } } } // // X509 Certificate Extensions // // Extensions we will add to the certificate, later when we have filled the structure with // everything we want. final ExtensionsGenerator extgen = new ExtensionsGenerator(); // First we check if there is general extension override, and add all extensions from // the request in that case if (certProfile.getAllowExtensionOverride() && extensions != null) { ASN1ObjectIdentifier[] oids = extensions.getExtensionOIDs(); for (ASN1ObjectIdentifier oid : oids) { final Extension ext = extensions.getExtension(oid); if (log.isDebugEnabled()) { log.debug("Overriding extension with oid: " + oid); } try { extgen.addExtension(oid, ext.isCritical(), ext.getParsedValue()); } catch (IOException e) { throw new IllegalStateException("Caught unexpected IOException.", e); } } } // Second we see if there is Key usage override Extensions overridenexts = extgen.generate(); if (certProfile.getAllowKeyUsageOverride() && (keyusage >= 0)) { if (log.isDebugEnabled()) { log.debug("AllowKeyUsageOverride=true. Using KeyUsage from parameter: " + keyusage); } if ((certProfile.getUseKeyUsage() == true) && (keyusage >= 0)) { final KeyUsage ku = new KeyUsage(keyusage); // We don't want to try to add custom extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(Extension.keyUsage) == null) { try { extgen.addExtension(Extension.keyUsage, certProfile.getKeyUsageCritical(), ku); } catch (IOException e) { throw new IllegalStateException("Caught unexpected IOException.", e); } } else { if (log.isDebugEnabled()) { log.debug( "KeyUsage was already overridden by an extension, not using KeyUsage from parameter."); } } } } // Third, check for standard Certificate Extensions that should be added. // Standard certificate extensions are defined in CertificateProfile and CertificateExtensionFactory // and implemented in package org.ejbca.core.model.certextensions.standard final CertificateExtensionFactory fact = CertificateExtensionFactory.getInstance(); final List<String> usedStdCertExt = certProfile.getUsedStandardCertificateExtensions(); final Iterator<String> certStdExtIter = usedStdCertExt.iterator(); overridenexts = extgen.generate(); while (certStdExtIter.hasNext()) { final String oid = certStdExtIter.next(); // We don't want to try to add standard extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(new ASN1ObjectIdentifier(oid)) == null) { final CertificateExtension certExt = fact.getStandardCertificateExtension(oid, certProfile); if (certExt != null) { final byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey, val); if (value != null) { extgen.addExtension(new ASN1ObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(), value); } } } else { if (log.isDebugEnabled()) { log.debug("Extension with oid " + oid + " has been overridden, standard extension will not be added."); } } } // Fourth, check for custom Certificate Extensions that should be added. // Custom certificate extensions is defined in certextensions.properties final List<Integer> usedCertExt = certProfile.getUsedCertificateExtensions(); final Iterator<Integer> certExtIter = usedCertExt.iterator(); while (certExtIter.hasNext()) { final Integer id = certExtIter.next(); final CertificateExtension certExt = fact.getCertificateExtensions(id); if (certExt != null) { // We don't want to try to add custom extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(new ASN1ObjectIdentifier(certExt.getOID())) == null) { final byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey, val); if (value != null) { extgen.addExtension(new ASN1ObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(), value); } } else { if (log.isDebugEnabled()) { log.debug("Extension with oid " + certExt.getOID() + " has been overridden, custom extension will not be added."); } } } } // Finally add extensions to certificate generator final Extensions exts = extgen.generate(); ASN1ObjectIdentifier[] oids = exts.getExtensionOIDs(); try { for (ASN1ObjectIdentifier oid : oids) { final Extension extension = exts.getExtension(oid); if (oid.equals(Extension.subjectAlternativeName)) { // subjectAlternativeName extension value needs special handling ExtensionsGenerator sanExtGen = getSubjectAltNameExtensionForCert(extension, precertbuilder != null); Extensions sanExts = sanExtGen.generate(); Extension eext = sanExts.getExtension(oid); certbuilder.addExtension(oid, eext.isCritical(), eext.getParsedValue()); // adding subjetAlternativeName extension to certbuilder if (precertbuilder != null) { // if a pre-certificate is to be published to a CTLog eext = getSubjectAltNameExtensionForCTCert(extension).generate().getExtension(oid); precertbuilder.addExtension(oid, eext.isCritical(), eext.getParsedValue()); // adding subjectAlternativeName extension to precertbuilder eext = sanExts.getExtension(new ASN1ObjectIdentifier("1.3.6.1.4.1.11129.2.4.6")); if (eext != null) { certbuilder.addExtension(eext.getExtnId(), eext.isCritical(), eext.getParsedValue()); // adding nrOfRedactedLabels extension to certbuilder } } } else { // if not a subjectAlternativeName extension, just add it to both certbuilder and precertbuilder final boolean isCritical = extension.isCritical(); // We must get the raw octets here in order to be able to create invalid extensions that is not constructed from proper ASN.1 final byte[] value = extension.getExtnValue().getOctets(); certbuilder.addExtension(extension.getExtnId(), isCritical, value); if (precertbuilder != null) { precertbuilder.addExtension(extension.getExtnId(), isCritical, value); } } } // Add Certificate Transparency extension. It needs to access the certbuilder and // the CA key so it has to be processed here inside X509CA. if (ct != null && certProfile.isUseCertificateTransparencyInCerts() && certGenParams.getConfiguredCTLogs() != null && certGenParams.getCTAuditLogCallback() != null) { // Create pre-certificate // A critical extension is added to prevent this cert from being used ct.addPreCertPoison(precertbuilder); // Sign pre-certificate /* * TODO: Should be able to use a special CT signing certificate. * It should have CA=true and ExtKeyUsage=PRECERTIFICATE_SIGNING_OID, * and should not have any other key usages. */ final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(caPrivateKey), 20480); final X509CertificateHolder certHolder = precertbuilder.build(signer); final X509Certificate cert = (X509Certificate) CertTools .getCertfromByteArray(certHolder.getEncoded()); // Get certificate chain final List<Certificate> chain = new ArrayList<Certificate>(); chain.add(cert); chain.addAll(getCertificateChain()); // Submit to logs and get signed timestamps byte[] sctlist = null; try { sctlist = ct.fetchSCTList(chain, certProfile, certGenParams.getConfiguredCTLogs()); } finally { // Notify that pre-cert has been successfully or unsuccessfully submitted so it can be audit logged. certGenParams.getCTAuditLogCallback().logPreCertSubmission(this, subject, cert, sctlist != null); } if (sctlist != null) { // can be null if the CTLog has been deleted from the configuration ASN1ObjectIdentifier sctOid = new ASN1ObjectIdentifier(CertificateTransparency.SCTLIST_OID); certbuilder.addExtension(sctOid, false, new DEROctetString(sctlist)); } } else { if (log.isDebugEnabled()) { String cause = ""; if (ct == null) { cause += "CT is not available in this version of EJBCA."; } else { if (!certProfile.isUseCertificateTransparencyInCerts()) { cause += "CT is not enabled in the certificate profile. "; } if (certGenParams == null) { cause += "Certificate generation parameters was null."; } else if (certGenParams.getCTAuditLogCallback() == null) { cause += "No CT audit logging callback was passed to X509CA."; } else if (certGenParams.getConfiguredCTLogs() == null) { cause += "There are no CT logs configured in System Configuration."; } } log.debug("Not logging to CT. " + cause); } } } catch (CertificateException e) { throw new CertificateCreateException( "Could not process CA's private key when parsing Certificate Transparency extension.", e); } catch (IOException e) { throw new CertificateCreateException( "IOException was caught when parsing Certificate Transparency extension.", e); } catch (CTLogException e) { throw new CertificateCreateException( "An exception occurred because too many CT servers were down to satisfy the certificate profile.", e); } // // End of extensions // if (log.isTraceEnabled()) { log.trace(">certgen.generate"); } final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(caPrivateKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); X509Certificate cert; try { cert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException caught when parsing certificate holder.", e); } catch (CertificateException e) { throw new CertificateCreateException("Could not create certificate from CA's private key,", e); } if (log.isTraceEnabled()) { log.trace("<certgen.generate"); } // Verify using the CA certificate before returning // If we can not verify the issued certificate using the CA certificate we don't want to issue this cert // because something is wrong... final PublicKey verifyKey; // We must use the configured public key if this is a rootCA, because then we can renew our own certificate, after changing // the keys. In this case the _new_ key will not match the current CA certificate. if ((cacert != null) && (!isRootCA)) { verifyKey = cacert.getPublicKey(); } else { verifyKey = caPublicKey; } try { cert.verify(verifyKey); } catch (InvalidKeyException e) { throw new CertificateCreateException("CA's public key was invalid,", e); } catch (NoSuchAlgorithmException e) { throw new CertificateCreateException(e); } catch (NoSuchProviderException e) { throw new IllegalStateException("Provider was unknown", e); } catch (CertificateException e) { throw new CertificateCreateException(e); } // If we have a CA-certificate, verify that we have all path verification stuff correct if (cacert != null) { final byte[] aki = CertTools.getAuthorityKeyId(cert); final byte[] ski = CertTools.getSubjectKeyId(isRootCA ? cert : cacert); if ((aki != null) && (ski != null)) { final boolean eq = Arrays.equals(aki, ski); if (!eq) { final String akistr = new String(Hex.encode(aki)); final String skistr = new String(Hex.encode(ski)); final String msg = intres.getLocalizedMessage("createcert.errorpathverifykeyid", akistr, skistr); log.error(msg); // This will differ if we create link certificates, NewWithOld, therefore we can not throw an exception here. } } final Principal issuerDN = cert.getIssuerX500Principal(); final Principal caSubjectDN = cacert.getSubjectX500Principal(); if ((issuerDN != null) && (caSubjectDN != null)) { final boolean eq = issuerDN.equals(caSubjectDN); if (!eq) { final String msg = intres.getLocalizedMessage("createcert.errorpathverifydn", issuerDN.getName(), caSubjectDN.getName()); log.error(msg); throw new CertificateCreateException(msg); } } } // Before returning from this method, we will set the private key and provider in the request message, in case the response message needs to be signed if (request != null) { request.setResponseKeyInfo(caPrivateKey, provider); } if (log.isDebugEnabled()) { log.debug("X509CA: generated certificate, CA " + this.getCAId() + " for DN: " + subject.getCertificateDN()); } return cert; }