List of usage examples for org.bouncycastle.asn1.x509 Extension subjectAlternativeName
ASN1ObjectIdentifier subjectAlternativeName
To view the source code for org.bouncycastle.asn1.x509 Extension subjectAlternativeName.
Click Source Link
From source file:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java
License:Apache License
private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) { List<String> sans = new ArrayList<>(); Attribute[] certAttributes = csr.getAttributes(); for (Attribute attribute : certAttributes) { if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0)); GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); GeneralName[] names = gns.getNames(); for (GeneralName name : names) { logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName()); String title = ""; if (name.getTagNo() == GeneralName.dNSName) { title = "DNS"; } else if (name.getTagNo() == GeneralName.iPAddress) { title = "IP Address"; // name.toASN1Primitive(); } else if (name.getTagNo() == GeneralName.otherName) { title = "Other Name"; }/*from ww w.j a v a 2 s. c o m*/ sans.add(title + ": " + name.getName()); } } } return sans; }
From source file:org.apache.zookeeper.common.X509TestHelpers.java
License:Apache License
/** * Using the private key of the given CA key pair and the Subject of the given CA cert as the Issuer, issues a * new cert with the given subject and public key. The returned certificate, combined with the private key half * of the <code>certPublicKey</code>, should be used as the key store. * @param caCert the certificate of the CA that's doing the signing. * @param caKeyPair the key pair of the CA. The private key will be used to sign. The public key must match the * public key in the <code>caCert</code>. * @param certSubject the subject field of the new cert being issued. * @param certPublicKey the public key of the new cert being issued. * @param expirationMillis the expiration of the cert being issued, in milliseconds from now. * @return a new certificate signed by the CA's private key. * @throws IOException/* ww w . j a v a2s . c o m*/ * @throws OperatorCreationException * @throws GeneralSecurityException */ public static X509Certificate newCert(X509Certificate caCert, KeyPair caKeyPair, X500Name certSubject, PublicKey certPublicKey, long expirationMillis) throws IOException, OperatorCreationException, GeneralSecurityException { if (!caKeyPair.getPublic().equals(caCert.getPublicKey())) { throw new IllegalArgumentException("CA private key does not match the public key in the CA cert"); } Date now = new Date(); X509v3CertificateBuilder builder = initCertBuilder(new X500Name(caCert.getIssuerDN().getName()), now, new Date(now.getTime() + expirationMillis), certSubject, certPublicKey); builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); // not a CA builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); builder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth })); builder.addExtension(Extension.subjectAlternativeName, false, getLocalhostSubjectAltNames()); return buildAndSignCertificate(caKeyPair.getPrivate(), builder); }
From source file:org.apache.zookeeper.common.ZKTrustManagerTest.java
License:Apache License
private X509Certificate[] createSelfSignedCertifcateChain(String ipAddress, String hostname) throws Exception { X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, "NOT_LOCALHOST"); Date notBefore = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(notBefore);/*w ww . j a va 2 s . c o m*/ cal.add(Calendar.YEAR, 1); Date notAfter = cal.getTime(); BigInteger serialNumber = new BigInteger(128, new Random()); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic()) .addExtension(Extension.basicConstraints, true, new BasicConstraints(0)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); List<GeneralName> generalNames = new ArrayList<>(); if (ipAddress != null) { generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress)); } if (hostname != null) { generalNames.add(new GeneralName(GeneralName.dNSName, hostname)); } if (!generalNames.isEmpty()) { certificateBuilder.addExtension(Extension.subjectAlternativeName, true, new GeneralNames(generalNames.toArray(new GeneralName[] {}))); } ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); return new X509Certificate[] { new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner)) }; }
From source file:org.apache.zookeeper.server.quorum.QuorumSSLTest.java
License:Apache License
public X509Certificate buildEndEntityCert(KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivateKey, String hostname, String ipAddress, String crlPath, Integer ocspPort) throws Exception { X509CertificateHolder holder = new JcaX509CertificateHolder(caCert); ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPrivateKey); List<GeneralName> generalNames = new ArrayList<>(); if (hostname != null) { generalNames.add(new GeneralName(GeneralName.dNSName, hostname)); }// w w w . j ava 2 s. c o m if (ipAddress != null) { generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress)); } SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory .createSubjectPublicKeyInfo(PublicKeyFactory.createKey(keyPair.getPublic().getEncoded())); X509ExtensionUtils extensionUtils = new BcX509ExtensionUtils(); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(holder.getSubject(), new BigInteger(128, new Random()), certStartTime, certEndTime, new X500Name("CN=Test End Entity Certificate"), keyPair.getPublic()) .addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(holder)) .addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(entityKeyInfo)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(false)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); if (!generalNames.isEmpty()) { certificateBuilder.addExtension(Extension.subjectAlternativeName, true, new GeneralNames(generalNames.toArray(new GeneralName[] {}))); } if (crlPath != null) { DistributionPointName distPointOne = new DistributionPointName( new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, "file://" + crlPath))); certificateBuilder.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(new DistributionPoint[] { new DistributionPoint(distPointOne, null, null) })); } if (ocspPort != null) { certificateBuilder.addExtension(Extension.authorityInfoAccess, false, new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + hostname + ":" + ocspPort))); } return new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(signer)); }
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
/** * 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. * /* w w w . jav a2 s . com*/ * @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; }
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
/** * Constructs the SubjectAlternativeName extension that will end up on the generated certificate. * /*from w w w.java2 s .co m*/ * If the DNS values in the subjectAlternativeName extension contain parentheses to specify labels that should be redacted, the parentheses are removed and another extension * containing the number of redacted labels is added. * * @param subAltNameExt * @param publishToCT * @return An extension generator containing the SubjectAlternativeName extension and an extension holding the number of redacted labels if the certificate is to be published * to a CTLog * @throws IOException */ private ExtensionsGenerator getSubjectAltNameExtensionForCert(Extension subAltNameExt, boolean publishToCT) throws IOException { String subAltName = CertTools.getAltNameStringFromExtension(subAltNameExt); List<String> dnsValues = CertTools.getPartsFromDN(subAltName, CertTools.DNS); int[] nrOfRecactedLables = new int[dnsValues.size()]; boolean sanEdited = false; int i = 0; for (String dns : dnsValues) { if (StringUtils.contains(dns, "(") && StringUtils.contains(dns, ")")) { // if it contains parts that should be redacted // Remove the parentheses from the SubjectAltName that will end up on the certificate String certBuilderDNSValue = StringUtils.remove(dns, '('); certBuilderDNSValue = StringUtils.remove(certBuilderDNSValue, ')'); subAltName = StringUtils.replace(subAltName, dns, certBuilderDNSValue); sanEdited = true; if (publishToCT) { String redactedLable = StringUtils.substring(dns, StringUtils.indexOf(dns, "("), StringUtils.lastIndexOf(dns, ")") + 1); // tex. (top.secret).domain.se => redactedLable = (top.secret) aka. including the parentheses nrOfRecactedLables[i] = StringUtils.countMatches(redactedLable, ".") + 1; } } i++; } ExtensionsGenerator gen = new ExtensionsGenerator(); gen.addExtension(Extension.subjectAlternativeName, subAltNameExt.isCritical(), CertTools.getGeneralNamesFromAltName(subAltName)); // If there actually are redacted parts, add the extension containing the number of redacted lables to the certificate if (publishToCT && sanEdited) { ASN1EncodableVector v = new ASN1EncodableVector(); for (int val : nrOfRecactedLables) { v.add(new ASN1Integer(val)); } ASN1Encodable seq = new DERSequence(v); gen.addExtension(new ASN1ObjectIdentifier("1.3.6.1.4.1.11129.2.4.6"), false, seq); } return gen; }
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
/** * Constructs the SubjectAlternativeName extension that will end up on the certificate published to a CTLog * /* www . j a v a 2 s . c o m*/ * If the DNS values in the subjectAlternativeName extension contain parentheses to specify labels that should be redacted, these labels will be replaced by the string "PRIVATE" * * @param subAltNameExt * @returnAn extension generator containing the SubjectAlternativeName extension * @throws IOException */ private ExtensionsGenerator getSubjectAltNameExtensionForCTCert(Extension subAltNameExt) throws IOException { String subAltName = CertTools.getAltNameStringFromExtension(subAltNameExt); List<String> dnsValues = CertTools.getPartsFromDN(subAltName, CertTools.DNS); for (String dns : dnsValues) { if (StringUtils.contains(dns, "(") && StringUtils.contains(dns, ")")) { // if it contains parts that should be redacted String redactedLable = StringUtils.substring(dns, StringUtils.indexOf(dns, "("), StringUtils.lastIndexOf(dns, ")") + 1); // tex. (top.secret).domain.se => redactedLable = (top.secret) aka. including the parentheses subAltName = StringUtils.replace(subAltName, redactedLable, "(PRIVATE)"); } } ExtensionsGenerator gen = new ExtensionsGenerator(); gen.addExtension(Extension.subjectAlternativeName, subAltNameExt.isCritical(), CertTools.getGeneralNamesFromAltName(subAltName).getEncoded()); return gen; }
From source file:org.cesecore.certificates.ca.X509CATest.java
License:Open Source License
@SuppressWarnings("unchecked") private void doTestX509CABasicOperations(String algName) throws Exception { final CryptoToken cryptoToken = getNewCryptoToken(); final X509CA x509ca = createTestCA(cryptoToken, CADN); Certificate cacert = x509ca.getCACertificate(); // Start by creating a PKCS7 byte[] p7 = x509ca.createPKCS7(cryptoToken, cacert, true); assertNotNull(p7);/*from w ww.j av a 2 s . c o m*/ CMSSignedData s = new CMSSignedData(p7); Store certstore = s.getCertificates(); Collection<X509CertificateHolder> certs = certstore.getMatches(null); assertEquals(2, certs.size()); p7 = x509ca.createPKCS7(cryptoToken, cacert, false); assertNotNull(p7); s = new CMSSignedData(p7); certstore = s.getCertificates(); certs = certstore.getMatches(null); assertEquals(1, certs.size()); // Create a certificate request (will be pkcs10) byte[] req = x509ca.createRequest(cryptoToken, null, algName, cacert, CATokenConstants.CAKEYPURPOSE_CERTSIGN); PKCS10CertificationRequest p10 = new PKCS10CertificationRequest(req); assertNotNull(p10); String dn = p10.getSubject().toString(); assertEquals(CADN, dn); // Make a request with some pkcs11 attributes as well Collection<ASN1Encodable> attributes = new ArrayList<ASN1Encodable>(); // Add a subject alternative name ASN1EncodableVector altnameattr = new ASN1EncodableVector(); altnameattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foobar.bar.com"); ExtensionsGenerator extgen = new ExtensionsGenerator(); extgen.addExtension(Extension.subjectAlternativeName, false, san); Extensions exts = extgen.generate(); altnameattr.add(new DERSet(exts)); // Add a challenge password as well ASN1EncodableVector pwdattr = new ASN1EncodableVector(); pwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword); ASN1EncodableVector pwdvalues = new ASN1EncodableVector(); pwdvalues.add(new DERUTF8String("foobar123")); pwdattr.add(new DERSet(pwdvalues)); attributes.add(new DERSequence(altnameattr)); attributes.add(new DERSequence(pwdattr)); // create the p10 req = x509ca.createRequest(cryptoToken, attributes, algName, cacert, CATokenConstants.CAKEYPURPOSE_CERTSIGN); p10 = new PKCS10CertificationRequest(req); assertNotNull(p10); dn = p10.getSubject().toString(); assertEquals(CADN, dn); Attribute[] attrs = p10.getAttributes(); assertEquals(2, attrs.length); PKCS10RequestMessage p10msg = new PKCS10RequestMessage(new JcaPKCS10CertificationRequest(p10)); assertEquals("foobar123", p10msg.getPassword()); assertEquals("dNSName=foobar.bar.com", p10msg.getRequestAltNames()); try { x509ca.createAuthCertSignRequest(cryptoToken, p10.getEncoded()); } catch (UnsupportedOperationException e) { // Expected for a X509 CA } // Generate a client certificate and check that it was generated correctly EndEntityInformation user = new EndEntityInformation("username", "CN=User", 666, "rfc822Name=user@user.com", "user@user.com", new EndEntityType(EndEntityTypes.ENDUSER), 0, 0, EndEntityConstants.TOKEN_USERGEN, 0, null); KeyPair keypair = genTestKeyPair(algName); CertificateProfile cp = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); cp.addCertificatePolicy(new CertificatePolicy("1.1.1.2", null, null)); cp.setUseCertificatePolicies(true); Certificate usercert = x509ca.generateCertificate(cryptoToken, user, keypair.getPublic(), 0, null, 10L, cp, "00000"); assertNotNull(usercert); assertEquals("CN=User", CertTools.getSubjectDN(usercert)); assertEquals(CADN, CertTools.getIssuerDN(usercert)); assertEquals(getTestKeyPairAlgName(algName).toUpperCase(), AlgorithmTools.getCertSignatureAlgorithmNameAsString(usercert).toUpperCase()); assertEquals(new String(CertTools.getSubjectKeyId(cacert)), new String(CertTools.getAuthorityKeyId(usercert))); assertEquals("user@user.com", CertTools.getEMailAddress(usercert)); assertEquals("rfc822name=user@user.com", CertTools.getSubjectAlternativeName(usercert)); assertNull(CertTools.getUPNAltName(usercert)); assertFalse(CertTools.isSelfSigned(usercert)); usercert.verify(cryptoToken .getPublicKey(x509ca.getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN))); usercert.verify(x509ca.getCACertificate().getPublicKey()); assertTrue(CertTools.isCA(x509ca.getCACertificate())); assertFalse(CertTools.isCA(usercert)); assertEquals("1.1.1.2", CertTools.getCertificatePolicyId(usercert, 0)); X509Certificate cert = (X509Certificate) usercert; boolean[] ku = cert.getKeyUsage(); assertTrue(ku[0]); assertTrue(ku[1]); assertTrue(ku[2]); assertFalse(ku[3]); assertFalse(ku[4]); assertFalse(ku[5]); assertFalse(ku[6]); assertFalse(ku[7]); int bcku = CertTools.sunKeyUsageToBC(ku); assertEquals(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation | X509KeyUsage.keyEncipherment, bcku); // Create a CRL Collection<RevokedCertInfo> revcerts = new ArrayList<RevokedCertInfo>(); X509CRLHolder crl = x509ca.generateCRL(cryptoToken, revcerts, 1); assertNotNull(crl); X509CRL xcrl = CertTools.getCRLfromByteArray(crl.getEncoded()); assertEquals(CADN, CertTools.getIssuerDN(xcrl)); Set<?> set = xcrl.getRevokedCertificates(); assertNull(set); BigInteger num = CrlExtensions.getCrlNumber(xcrl); assertEquals(1, num.intValue()); BigInteger deltanum = CrlExtensions.getDeltaCRLIndicator(xcrl); assertEquals(-1, deltanum.intValue()); // Revoke some cert Date revDate = new Date(); revcerts.add(new RevokedCertInfo(CertTools.getFingerprintAsString(usercert).getBytes(), CertTools.getSerialNumber(usercert).toByteArray(), revDate.getTime(), RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, CertTools.getNotAfter(usercert).getTime())); crl = x509ca.generateCRL(cryptoToken, revcerts, 2); assertNotNull(crl); xcrl = CertTools.getCRLfromByteArray(crl.getEncoded()); set = xcrl.getRevokedCertificates(); assertEquals(1, set.size()); num = CrlExtensions.getCrlNumber(xcrl); assertEquals(2, num.intValue()); X509CRLEntry entry = (X509CRLEntry) set.iterator().next(); assertEquals(CertTools.getSerialNumber(usercert).toString(), entry.getSerialNumber().toString()); assertEquals(revDate.toString(), entry.getRevocationDate().toString()); // Getting the revocation reason is a pita... byte[] extval = entry.getExtensionValue(Extension.reasonCode.getId()); ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(extval)); ASN1OctetString octs = (ASN1OctetString) aIn.readObject(); aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets())); ASN1Primitive obj = aIn.readObject(); CRLReason reason = CRLReason.getInstance((ASN1Enumerated) obj); assertEquals("CRLReason: certificateHold", reason.toString()); //DEROctetString ostr = (DEROctetString)obj; // Create a delta CRL revcerts = new ArrayList<RevokedCertInfo>(); crl = x509ca.generateDeltaCRL(cryptoToken, revcerts, 3, 2); assertNotNull(crl); xcrl = CertTools.getCRLfromByteArray(crl.getEncoded()); assertEquals(CADN, CertTools.getIssuerDN(xcrl)); set = xcrl.getRevokedCertificates(); assertNull(set); num = CrlExtensions.getCrlNumber(xcrl); assertEquals(3, num.intValue()); deltanum = CrlExtensions.getDeltaCRLIndicator(xcrl); assertEquals(2, deltanum.intValue()); revcerts.add(new RevokedCertInfo(CertTools.getFingerprintAsString(usercert).getBytes(), CertTools.getSerialNumber(usercert).toByteArray(), revDate.getTime(), RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, CertTools.getNotAfter(usercert).getTime())); crl = x509ca.generateDeltaCRL(cryptoToken, revcerts, 4, 3); assertNotNull(crl); xcrl = CertTools.getCRLfromByteArray(crl.getEncoded()); deltanum = CrlExtensions.getDeltaCRLIndicator(xcrl); assertEquals(3, deltanum.intValue()); set = xcrl.getRevokedCertificates(); assertEquals(1, set.size()); entry = (X509CRLEntry) set.iterator().next(); assertEquals(CertTools.getSerialNumber(usercert).toString(), entry.getSerialNumber().toString()); assertEquals(revDate.toString(), entry.getRevocationDate().toString()); // Getting the revocation reason is a pita... extval = entry.getExtensionValue(Extension.reasonCode.getId()); aIn = new ASN1InputStream(new ByteArrayInputStream(extval)); octs = (ASN1OctetString) aIn.readObject(); aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets())); obj = aIn.readObject(); reason = CRLReason.getInstance((ASN1Enumerated) obj); assertEquals("CRLReason: certificateHold", reason.toString()); }
From source file:org.cesecore.certificates.certificate.certextensions.standard.SubjectAltNames.java
License:Open Source License
@Override public void init(final CertificateProfile certProf) { super.setOID(Extension.subjectAlternativeName.getId()); super.setCriticalFlag(certProf.getSubjectAlternativeNameCritical()); }
From source file:org.cesecore.certificates.certificate.request.PKCS10RequestMessage.java
License:Open Source License
@Override public String getRequestAltNames() { String ret = null;/* w w w .j a v a2 s . co m*/ try { Extensions exts = getRequestExtensions(); if (exts != null) { Extension ext = exts.getExtension(Extension.subjectAlternativeName); if (ext != null) { // Finally read the value ret = CertTools.getAltNameStringFromExtension(ext); } else { if (log.isDebugEnabled()) { log.debug("no subject altName extension"); } } } } catch (IllegalArgumentException e) { if (log.isDebugEnabled()) { log.debug( "pkcs_9_extensionRequest does not contain Extensions that it should, ignoring invalid encoded extension request."); } } return ret; }