List of usage examples for org.bouncycastle.asn1.x509 GeneralName uniformResourceIdentifier
int uniformResourceIdentifier
To view the source code for org.bouncycastle.asn1.x509 GeneralName uniformResourceIdentifier.
Click Source Link
From source file:eu.europa.esig.dss.x509.crl.CRLUtils.java
License:Open Source License
private static void checkCriticalExtensions(final X509CRL x509CRL, final CRLValidity crlValidity) { final Set<String> criticalExtensionOIDs = x509CRL.getCriticalExtensionOIDs(); if ((criticalExtensionOIDs == null) || (criticalExtensionOIDs.size() == 0)) { crlValidity.setUnknownCriticalExtension(false); } else {//from w w w. j ava 2s .com byte[] extensionValue = x509CRL.getExtensionValue(Extension.issuingDistributionPoint.getId()); IssuingDistributionPoint issuingDistributionPoint = IssuingDistributionPoint .getInstance(ASN1OctetString.getInstance(extensionValue).getOctets()); final boolean onlyAttributeCerts = issuingDistributionPoint.onlyContainsAttributeCerts(); final boolean onlyCaCerts = issuingDistributionPoint.onlyContainsCACerts(); final boolean onlyUserCerts = issuingDistributionPoint.onlyContainsUserCerts(); final boolean indirectCrl = issuingDistributionPoint.isIndirectCRL(); ReasonFlags onlySomeReasons = issuingDistributionPoint.getOnlySomeReasons(); DistributionPointName distributionPoint = issuingDistributionPoint.getDistributionPoint(); boolean urlFound = false; if (DistributionPointName.FULL_NAME == distributionPoint.getType()) { final GeneralNames generalNames = (GeneralNames) distributionPoint.getName(); if ((generalNames != null) && (generalNames.getNames() != null) && (generalNames.getNames().length > 0)) { for (GeneralName generalName : generalNames.getNames()) { if (GeneralName.uniformResourceIdentifier == generalName.getTagNo()) { urlFound = true; } } } } if (!(onlyAttributeCerts && onlyCaCerts && onlyUserCerts && indirectCrl) && (onlySomeReasons == null) && urlFound) { crlValidity.setUnknownCriticalExtension(false); } } }
From source file:fi.aalto.cs.drumbeat.ClientCertificateCreator.java
License:Open Source License
public void addURI(String subjectAlternativeName) { sans.add(new GeneralName(GeneralName.uniformResourceIdentifier, subjectAlternativeName)); }
From source file:gui.ExtensionsPopup.java
private void addIssuerAltNameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addIssuerAltNameButtonActionPerformed String extension = issuerAltNameTextField.getText(); issuerAltNameTextField.setText(""); if (!extension.isEmpty()) { String extName = (String) issuerAltNameComboBox.getSelectedItem(); try {/*from w w w. j a v a 2 s . c om*/ switch (extName) { case "Other Name": generalNamesBuilder.addName(new GeneralName(GeneralName.otherName, extension)); break; case "RFC822 Name": generalNamesBuilder.addName(new GeneralName(GeneralName.rfc822Name, extension)); break; case "DNS Name": generalNamesBuilder.addName(new GeneralName(GeneralName.dNSName, extension)); break; case "x400 Address": generalNamesBuilder.addName(new GeneralName(GeneralName.x400Address, extension)); break; case "Directory Name": generalNamesBuilder .addName(new GeneralName(GeneralName.directoryName, new X500Name(extension))); break; case "EDI Party Name": generalNamesBuilder.addName(new GeneralName(GeneralName.ediPartyName, extension)); break; case "URI": generalNamesBuilder.addName(new GeneralName(GeneralName.uniformResourceIdentifier, extension)); break; case "IP Address": generalNamesBuilder.addName(new GeneralName(GeneralName.iPAddress, extension)); break; case "Registered ID": generalNamesBuilder.addName(new GeneralName(GeneralName.registeredID, extension)); break; } } catch (Exception e) { JOptionPane.showMessageDialog(this, Errors.EXTENSION_INVALID_FORMAT, "Error", JOptionPane.ERROR_MESSAGE); return; } issuerAltNameTextArea.append(extName + ": " + extension + "\n"); } }
From source file:mitm.common.security.crl.CRLDistributionPointsBuilder.java
License:Open Source License
public CRLDistPoint buildCRLDistPoint() { if (uris.size() == 0) { return null; }/*from w w w. j a v a2 s . co m*/ CRLDistPoint crlDistPoint; ASN1EncodableVector names = new ASN1EncodableVector(); for (String uri : uris) { GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(uri)); names.add(gn); } GeneralNames gns = GeneralNames.getInstance(new DERSequence(names)); DistributionPointName dpn = new DistributionPointName(DistributionPointName.FULL_NAME, gns); DistributionPoint distp = new DistributionPoint(dpn, null, null); crlDistPoint = CRLDistPoint.getInstance(new DERSequence(distp)); return crlDistPoint; }
From source file:mitm.common.security.crl.CRLDistributionPointsInspector.java
License:Open Source License
public static Set<String> getURIDistributionPointNames(CRLDistPoint crlDistPoint) throws CRLException { try {/* w ww. j a v a2 s. c o m*/ Set<String> uris = new HashSet<String>(); if (crlDistPoint == null) { return uris; } DistributionPoint[] distributionPoints = crlDistPoint.getDistributionPoints(); if (distributionPoints != null) { for (DistributionPoint distributionPoint : distributionPoints) { if (distributionPoint == null) { logger.debug("Distributionpoint is null."); continue; } DistributionPointName distributionPointName = distributionPoint.getDistributionPoint(); /* We will only return full names containing URIs */ if (distributionPointName != null && distributionPointName.getType() == DistributionPointName.FULL_NAME) { ASN1Encodable name = distributionPointName.getName(); if (name != null) { GeneralName[] names = GeneralNames.getInstance(name).getNames(); for (GeneralName generalName : names) { if (generalName != null && generalName.getTagNo() == GeneralName.uniformResourceIdentifier && generalName.getName() != null) { String uri = DERIA5String.getInstance(generalName.getName()).getString(); uris.add(uri); } } } } } } return uris; } catch (IllegalArgumentException e) { /* * Can be thrown when the CRL dist. point contains illegal ASN1. */ throw new CRLException("Error getting the CRL distribution point names.", e); } }
From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java
License:Apache License
public X509TrustManager getTrustManager(final Iterable<String> identitiesToTest, final CertificateMatcher clientVerifier, final CertificateMatcher serverVerifier) throws GeneralSecurityException { // obtain the default X509 trust manager X509TrustManager defaultTm = null; TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); //workaround for https://bugs.openjdk.java.net/browse/JDK-6672015 KeyStore ks = null;/*from ww w . jav a2 s . co m*/ String tsType = System.getProperty("javax.net.ssl.trustStoreType", null); if ("Windows-ROOT".equals(tsType)) { try { ks = KeyStore.getInstance(tsType); ks.load(null, null); int numEntries = keyStoreAppendIndex(ks); logger.info( "Using Windows-ROOT. Aliases sucessfully renamed on " + numEntries + " root certificates."); } catch (Exception e) { logger.error("Could not rename Windows-ROOT aliases", e); } } tmFactory.init(ks); for (TrustManager m : tmFactory.getTrustManagers()) { if (m instanceof X509TrustManager) { defaultTm = (X509TrustManager) m; break; } } if (defaultTm == null) throw new GeneralSecurityException("No default X509 trust manager found"); final X509TrustManager tm = defaultTm; return new X509TrustManager() { private boolean serverCheck; public X509Certificate[] getAcceptedIssuers() { return tm.getAcceptedIssuers(); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { serverCheck = true; checkCertTrusted(chain, authType); } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { serverCheck = false; checkCertTrusted(chain, authType); } private void checkCertTrusted(X509Certificate[] chain, String authType) throws CertificateException { // check and default configurations for property // if missing default is null - false String defaultAlwaysTrustMode = CertificateVerificationActivator.getResources() .getSettingsString(CertificateService.PNAME_ALWAYS_TRUST); if (config.getBoolean(PNAME_ALWAYS_TRUST, Boolean.parseBoolean(defaultAlwaysTrustMode))) return; try { // check the certificate itself (issuer, validity) try { chain = tryBuildChain(chain); } catch (Exception e) { } // don't care and take the chain as is if (serverCheck) tm.checkServerTrusted(chain, authType); else tm.checkClientTrusted(chain, authType); if (identitiesToTest == null || !identitiesToTest.iterator().hasNext()) return; else if (serverCheck) serverVerifier.verify(identitiesToTest, chain[0]); else clientVerifier.verify(identitiesToTest, chain[0]); // ok, globally valid cert } catch (CertificateException e) { String thumbprint = getThumbprint(chain[0], THUMBPRINT_HASH_ALGORITHM); String message = null; List<String> propNames = new LinkedList<String>(); List<String> storedCerts = new LinkedList<String>(); String appName = R.getSettingsString("service.gui.APPLICATION_NAME"); if (identitiesToTest == null || !identitiesToTest.iterator().hasNext()) { String propName = PNAME_CERT_TRUST_PREFIX + ".server." + thumbprint; propNames.add(propName); message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT_NOHOST", new String[] { appName }); // get the thumbprints from the permanent allowances String hashes = config.getString(propName); if (hashes != null) for (String h : hashes.split(",")) storedCerts.add(h); // get the thumbprints from the session allowances List<String> sessionCerts = sessionAllowedCertificates.get(propName); if (sessionCerts != null) storedCerts.addAll(sessionCerts); } else { if (serverCheck) { message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT", new String[] { appName, identitiesToTest.toString() }); } else { message = R.getI18NString("service.gui." + "CERT_DIALOG_PEER_DESCRIPTION_TXT", new String[] { appName, identitiesToTest.toString() }); } for (String identity : identitiesToTest) { String propName = PNAME_CERT_TRUST_PREFIX + ".param." + identity; propNames.add(propName); // get the thumbprints from the permanent allowances String hashes = config.getString(propName); if (hashes != null) for (String h : hashes.split(",")) storedCerts.add(h); // get the thumbprints from the session allowances List<String> sessionCerts = sessionAllowedCertificates.get(propName); if (sessionCerts != null) storedCerts.addAll(sessionCerts); } } if (!storedCerts.contains(thumbprint)) { switch (verify(chain, message)) { case DO_NOT_TRUST: logger.info("Untrusted certificate", e); throw new CertificateException("The peer provided certificate with Subject <" + chain[0].getSubjectDN() + "> is not trusted", e); case TRUST_ALWAYS: for (String propName : propNames) { String current = config.getString(propName); String newValue = thumbprint; if (current != null) newValue += "," + current; config.setProperty(propName, newValue); } break; case TRUST_THIS_SESSION_ONLY: for (String propName : propNames) getSessionCertEntry(propName).add(thumbprint); break; } } // ok, we've seen this certificate before } } private X509Certificate[] tryBuildChain(X509Certificate[] chain) throws IOException, URISyntaxException, CertificateException { // Only try to build chains for servers that send only their // own cert, but no issuer. This also matches self signed (will // be ignored later) and Root-CA signed certs. In this case we // throw the Root-CA away after the lookup if (chain.length != 1) return chain; // ignore self signed certs if (chain[0].getIssuerDN().equals(chain[0].getSubjectDN())) return chain; // prepare for the newly created chain List<X509Certificate> newChain = new ArrayList<X509Certificate>(chain.length + 4); for (X509Certificate cert : chain) { newChain.add(cert); } // search from the topmost certificate upwards CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); X509Certificate current = chain[chain.length - 1]; boolean foundParent; int chainLookupCount = 0; do { foundParent = false; // extract the url(s) where the parent certificate can be // found byte[] aiaBytes = current.getExtensionValue(Extension.authorityInfoAccess.getId()); if (aiaBytes == null) break; AuthorityInformationAccess aia = AuthorityInformationAccess .getInstance(X509ExtensionUtil.fromExtensionValue(aiaBytes)); // the AIA may contain different URLs and types, try all // of them for (AccessDescription ad : aia.getAccessDescriptions()) { // we are only interested in the issuer certificate, // not in OCSP urls the like if (!ad.getAccessMethod().equals(AccessDescription.id_ad_caIssuers)) continue; GeneralName gn = ad.getAccessLocation(); if (!(gn.getTagNo() == GeneralName.uniformResourceIdentifier && gn.getName() instanceof DERIA5String)) continue; URI uri = new URI(((DERIA5String) gn.getName()).getString()); // only http(s) urls; LDAP is taken care of in the // default implementation if (!(uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equals("https"))) continue; X509Certificate cert = null; // try to get cert from cache first to avoid consecutive // (slow) http lookups AiaCacheEntry cache = aiaCache.get(uri); if (cache != null && cache.cacheDate.after(new Date())) { cert = cache.cert; } else { // download if no cache entry or if it is expired if (logger.isDebugEnabled()) logger.debug("Downloading parent certificate for <" + current.getSubjectDN() + "> from <" + uri + ">"); try { InputStream is = HttpUtils.openURLConnection(uri.toString()).getContent(); cert = (X509Certificate) certFactory.generateCertificate(is); } catch (Exception e) { logger.debug("Could not download from <" + uri + ">"); } // cache for 10mins aiaCache.put(uri, new AiaCacheEntry(new Date(new Date().getTime() + 10 * 60 * 1000), cert)); } if (cert != null) { if (!cert.getIssuerDN().equals(cert.getSubjectDN())) { newChain.add(cert); foundParent = true; current = cert; break; // an AD was valid, ignore others } else logger.debug("Parent is self-signed, ignoring"); } } chainLookupCount++; } while (foundParent && chainLookupCount < 10); chain = newChain.toArray(chain); return chain; } }; }
From source file:net.link.util.common.KeyUtils.java
License:Open Source License
public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, PrivateKey issuerPrivateKey, @Nullable X509Certificate issuerCert, DateTime notBefore, DateTime notAfter, String inSignatureAlgorithm, boolean caCert, boolean timeStampingPurpose, @Nullable URI ocspUri) {//from www . j a v a 2 s .c om try { String signatureAlgorithm = inSignatureAlgorithm; if (null == signatureAlgorithm) signatureAlgorithm = String.format("SHA1With%s", issuerPrivateKey.getAlgorithm()); X509Principal issuerDN; if (null != issuerCert) issuerDN = new X509Principal(issuerCert.getSubjectX500Principal().toString()); else issuerDN = new X509Principal(subjectDn); // new bc 2.0 API X509Principal subject = new X509Principal(subjectDn); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded()); BigInteger serialNumber = new BigInteger(SERIALNUMBER_NUM_BITS, new SecureRandom()); X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder( X500Name.getInstance(issuerDN.toASN1Primitive()), serialNumber, notBefore.toDate(), notAfter.toDate(), X500Name.getInstance(subject.toASN1Primitive()), publicKeyInfo); // prepare signer ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(issuerPrivateKey); certificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, createSubjectKeyId(subjectPublicKey)); PublicKey issuerPublicKey; if (null != issuerCert) issuerPublicKey = issuerCert.getPublicKey(); else issuerPublicKey = subjectPublicKey; certificateBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, createAuthorityKeyId(issuerPublicKey)); certificateBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(caCert)); if (timeStampingPurpose) certificateBuilder.addExtension(X509Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping)); if (null != ocspUri) { GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri.toString()); AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, ocspName); certificateBuilder.addExtension(X509Extension.authorityInfoAccess, false, authorityInformationAccess); } // build return new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certificateBuilder.build(signer)); } catch (CertificateException e) { throw new InternalInconsistencyException("X.509 is not supported.", e); } catch (OperatorCreationException e) { throw new InternalInconsistencyException(e); } catch (CertIOException e) { throw new InternalInconsistencyException(e); } }
From source file:net.link.util.test.pkix.PkiTestUtils.java
License:Open Source License
public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, PrivateKey issuerPrivateKey, @Nullable X509Certificate issuerCert, DateTime notBefore, DateTime notAfter, @Nullable String signatureAlgorithm, boolean includeAuthorityKeyIdentifier, boolean caCert, boolean timeStampingPurpose, @Nullable URI ocspUri) throws IOException, CertificateException, OperatorCreationException { String finalSignatureAlgorithm = signatureAlgorithm; if (null == signatureAlgorithm) finalSignatureAlgorithm = "SHA512WithRSAEncryption"; X509Principal issuerDN;/* w ww . j av a 2s . c om*/ if (null != issuerCert) issuerDN = new X509Principal(issuerCert.getSubjectX500Principal().toString()); else issuerDN = new X509Principal(subjectDn); // new bc 2.0 API X509Principal subject = new X509Principal(subjectDn); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded()); BigInteger serialNumber = new BigInteger(SERIALNUMBER_NUM_BITS, new SecureRandom()); X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder( X500Name.getInstance(issuerDN.toASN1Primitive()), serialNumber, notBefore.toDate(), notAfter.toDate(), X500Name.getInstance(subject.toASN1Primitive()), publicKeyInfo); // prepare signer ContentSigner signer = new JcaContentSignerBuilder(finalSignatureAlgorithm).build(issuerPrivateKey); // add extensions certificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, createSubjectKeyId(subjectPublicKey)); PublicKey issuerPublicKey; if (null != issuerCert) issuerPublicKey = issuerCert.getPublicKey(); else issuerPublicKey = subjectPublicKey; if (includeAuthorityKeyIdentifier) certificateBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, createAuthorityKeyId(issuerPublicKey)); certificateBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(caCert)); if (timeStampingPurpose) certificateBuilder.addExtension(X509Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping)); if (null != ocspUri) { GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(ocspUri.toString())); AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, ocspName); certificateBuilder.addExtension(X509Extension.authorityInfoAccess, false, authorityInformationAccess); } // build return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateBuilder.build(signer)); }
From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java
License:Apache License
/** * Builds and signs a certificate. The certificate will be build on the given subject-public-key and signed with * the given issuer-private-key. The issuer and subject will be identified in the strings provided. * * @return A signed X509Certificate/*from w w w. ja v a 2s .com*/ * @throws Exception */ public X509Certificate buildAndSignCert(BigInteger serialNumber, PrivateKey signerPrivateKey, PublicKey signerPublicKey, PublicKey subjectPublicKey, X500Name issuer, X500Name subject, Map<String, String> customAttrs, String type) throws Exception { // Dates are converted to GMT/UTC inside the cert builder Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); Date expire = new GregorianCalendar(CERT_EXPIRE_YEAR, 0, 1).getTime(); X509v3CertificateBuilder certV3Bldr = new JcaX509v3CertificateBuilder(issuer, serialNumber, now, // Valid from now... expire, // until CERT_EXPIRE_YEAR subject, subjectPublicKey); JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils(); // Create certificate extensions if ("ROOTCA".equals(type)) { certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign)); } else if ("INTERMEDIATE".equals(type)) { certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign)); } else { // Subject Alternative Name GeneralName[] genNames = null; if (customAttrs != null && !customAttrs.isEmpty()) { genNames = new GeneralName[customAttrs.size()]; Iterator<Map.Entry<String, String>> it = customAttrs.entrySet().iterator(); int idx = 0; while (it.hasNext()) { Map.Entry<String, String> pair = it.next(); //genNames[idx] = new GeneralName(GeneralName.otherName, new DERUTF8String(pair.getKey() + ";" + pair.getValue())); DERSequence othernameSequence = new DERSequence( new ASN1Encodable[] { new ASN1ObjectIdentifier(pair.getKey()), new DERTaggedObject(true, 0, new DERUTF8String(pair.getValue())) }); genNames[idx] = new GeneralName(GeneralName.otherName, othernameSequence); idx++; } } if (genNames != null) { certV3Bldr = certV3Bldr.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(genNames)); } } // Basic extension setup certV3Bldr = certV3Bldr .addExtension(Extension.authorityKeyIdentifier, false, extensionUtil.createAuthorityKeyIdentifier(signerPublicKey)) .addExtension(Extension.subjectKeyIdentifier, false, extensionUtil.createSubjectKeyIdentifier(subjectPublicKey)); // CRL Distribution Points DistributionPointName distPointOne = new DistributionPointName( new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, CRL_URL))); DistributionPoint[] distPoints = new DistributionPoint[1]; distPoints[0] = new DistributionPoint(distPointOne, null, null); certV3Bldr.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints)); // OCSP endpoint GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, OCSP_URL); AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, ocspName); certV3Bldr.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess); // Create the key signer JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNER_ALGORITHM); builder.setProvider(BC_PROVIDER_NAME); ContentSigner signer = builder.build(signerPrivateKey); return new JcaX509CertificateConverter().setProvider(BC_PROVIDER_NAME) .getCertificate(certV3Bldr.build(signer)); }
From source file:net.maritimecloud.pki.CertificateBuilder.java
License:Apache License
/** * Builds and signs a certificate. The certificate will be build on the given subject-public-key and signed with * the given issuer-private-key. The issuer and subject will be identified in the strings provided. * * @param serialNumber The serialnumber of the new certificate. * @param signerPrivateKey Private key for signing the certificate * @param signerPublicKey Public key of the signing certificate * @param subjectPublicKey Public key for the new certificate * @param issuer DN of the signing certificate * @param subject DN of the new certificate * @param customAttrs The custom MC attributes to include in the certificate * @param type Type of certificate, can be "ROOT", "INTERMEDIATE" or "ENTITY". * @param ocspUrl OCSP endpoint//from w ww .j a v a2 s . co m * @param crlUrl CRL endpoint - can be null * @return A signed X509Certificate * @throws Exception Throws exception on certificate generation errors. */ public X509Certificate buildAndSignCert(BigInteger serialNumber, PrivateKey signerPrivateKey, PublicKey signerPublicKey, PublicKey subjectPublicKey, X500Name issuer, X500Name subject, Map<String, String> customAttrs, String type, String ocspUrl, String crlUrl) throws Exception { // Dates are converted to GMT/UTC inside the cert builder Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); Date expire = new GregorianCalendar(CERT_EXPIRE_YEAR, 0, 1).getTime(); X509v3CertificateBuilder certV3Bldr = new JcaX509v3CertificateBuilder(issuer, serialNumber, now, // Valid from now... expire, // until CERT_EXPIRE_YEAR subject, subjectPublicKey); JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils(); // Create certificate extensions if ("ROOTCA".equals(type)) { certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign)); } else if ("INTERMEDIATE".equals(type)) { certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign)); } else { // Subject Alternative Name GeneralName[] genNames = null; if (customAttrs != null && !customAttrs.isEmpty()) { genNames = new GeneralName[customAttrs.size()]; Iterator<Map.Entry<String, String>> it = customAttrs.entrySet().iterator(); int idx = 0; while (it.hasNext()) { Map.Entry<String, String> pair = it.next(); if (PKIConstants.X509_SAN_DNSNAME.equals(pair.getKey())) { genNames[idx] = new GeneralName(GeneralName.dNSName, pair.getValue()); } else { //genNames[idx] = new GeneralName(GeneralName.otherName, new DERUTF8String(pair.getKey() + ";" + pair.getValue())); DERSequence othernameSequence = new DERSequence( new ASN1Encodable[] { new ASN1ObjectIdentifier(pair.getKey()), new DERTaggedObject(true, 0, new DERUTF8String(pair.getValue())) }); genNames[idx] = new GeneralName(GeneralName.otherName, othernameSequence); } idx++; } } if (genNames != null) { certV3Bldr = certV3Bldr.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(genNames)); } } // Basic extension setup certV3Bldr = certV3Bldr .addExtension(Extension.authorityKeyIdentifier, false, extensionUtil.createAuthorityKeyIdentifier(signerPublicKey)) .addExtension(Extension.subjectKeyIdentifier, false, extensionUtil.createSubjectKeyIdentifier(subjectPublicKey)); // CRL Distribution Points DistributionPointName distPointOne = new DistributionPointName( new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, crlUrl))); DistributionPoint[] distPoints = new DistributionPoint[1]; distPoints[0] = new DistributionPoint(distPointOne, null, null); certV3Bldr.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints)); // OCSP endpoint - is not available for the CAs if (ocspUrl != null) { GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUrl); AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, ocspName); certV3Bldr.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess); } // Create the key signer JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNER_ALGORITHM); builder.setProvider(BC_PROVIDER_NAME); ContentSigner signer = builder.build(signerPrivateKey); return new JcaX509CertificateConverter().setProvider(BC_PROVIDER_NAME) .getCertificate(certV3Bldr.build(signer)); }