Creates a new SSL certificate signed by the CA private key and stored in
keyStore.

@param sslMetadata
@param caPrivateKey
@param caCert
@param targetStoreFile
@param x509log
422526
public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetStoreFile, X509Log x509log) {
        try {
            KeyPair pair = newKeyPair();

            X500Name webDN = buildDistinguishedName(sslMetadata);
            X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());

            X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
                    issuerDN,
                    BigInteger.valueOf(System.currentTimeMillis()),
                    sslMetadata.notBefore,
                    sslMetadata.notAfter,
                    webDN,
                    pair.getPublic());

            JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
            certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
            certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
            certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));

            // support alternateSubjectNames for SSL certificates
            List<GeneralName> altNames = new ArrayList<GeneralName>();
            if (isIpAddress(sslMetadata.commonName)) {
                altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName));
            }
            if (altNames.size() > 0) {
                GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName[altNames.size()]));
                certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
            }

            ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM)
                    .setProvider(BC).build(caPrivateKey);
            X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
                    .getCertificate(certBuilder.build(caSigner));

            cert.checkValidity(new Date());
            cert.verify(caCert.getPublicKey());

            // Save to keystore
            KeyStore serverStore = openKeyStore(targetStoreFile, sslMetadata.password);
            serverStore.setKeyEntry(sslMetadata.commonName, pair.getPrivate(), sslMetadata.password.toCharArray(),
                    new Certificate[]{cert, caCert});
            saveKeyStore(targetStoreFile, serverStore, sslMetadata.password);

            x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getSubjectDN().getName()));

            // update serial number in metadata object
            sslMetadata.serialNumber = cert.getSerialNumber().toString();

            return cert;
        } catch (Throwable t) {
            throw new RuntimeException("Failed to generate SSL certificate!", t);
        }
    }
1266648
public static CertStore createCertStore(TrustedCertificates tc) throws Exception {

        CertStore store = null;
        if (tc == null) {
            String caCertPattern = "file:" + CoGProperties.getDefault().getCaCertLocations() + "/*.0";
            store = Stores.getCACertStore(caCertPattern);
        } else {
            SimpleMemoryCertStoreParams params = new SimpleMemoryCertStoreParams(tc.getCertificates(), null);
            params.setCerts(tc.getCertificates());
            store = CertStore.getInstance(SimpleMemoryProvider.CERTSTORE_TYPE, params, SimpleMemoryProvider.PROVIDER_NAME);
        }
        return store;
    }
767227
void setCertificateToTruststore(X509Certificate[] chain) throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "setCertificateToTruststore");

        try {

            WSKeyStore wsks = KeyStoreManager.getInstance().getKeyStore(tsCfgAlias);
            if (wsks == null)
                throw (new Exception("Keystore " + tsCfgAlias + " does not exist in the configuration."));
            if (wsks.getReadOnly()) {
                issueMessage("ssl.keystore.readonly.CWPKI0810I",
                             new Object[] { tsCfgAlias },
                             "The "
                                             + tsCfgAlias
                                             + " keystore is read only and the certificate will not be written to the keystore file.  Trust will be accepted only for this connection.");

            } else {
                for (int j = 0; j < chain.length; j++) {
                    String alias = chain[j].getSubjectDN().getName();
                    alias = alias.trim();

                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Adding alias \"" + alias + "\" to truststore \"" + tsFile + "\".");
                    wsks.setCertificateEntry(alias, chain[chain.length - 1]);
                    String shaDigest = KeyStoreManager.getInstance().generateDigest("SHA-1", chain[chain.length - 1]);

                    issueMessage("ssl.signer.add.to.local.truststore.CWPKI0308I", new Object[] { alias, tsFile, shaDigest }, "CWPKI0308I: Adding signer alias \"" + alias
                                                                                                                             + "\" to local keystore \"" + tsFile
                                                                                                                             + "\" with the following SHA digest: " + shaDigest);

                    //Certificate is set on the truststore now clear the caches, if the file monitor is on let it handle the change.
                    String trigger = wsks.getTrigger();
                    if (!trigger.equalsIgnoreCase("disabled"))
                        clearSSLCachesAndResetDefault();
                }
            }
        } catch (Exception e) {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Exception while trying to write certificate to the truststore. Exception is " + e.getMessage());
            throw e;
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "setCertificateToTruststore");
    }
702648
@Override
	public X509Certificate sign(Trans trans, CSRMeta csrmeta) throws IOException, CertException {
		GregorianCalendar gc = new GregorianCalendar();
		Date start = gc.getTime();
		gc.add(GregorianCalendar.DAY_OF_MONTH, 1);
		Date end = gc.getTime();
		X509Certificate x509;
		TimeTaken tt = trans.start("Create/Sign Cert",Env.SUB);
		try {
			BigInteger bi;
			synchronized(serialish) {
				random.nextBytes(serialish);
				bi = new BigInteger(serialish);
			}
				
			X509v3CertificateBuilder xcb = new X509v3CertificateBuilder(
					issuer,
					bi, // replace with Serialnumber scheme
					start,
					end,
					csrmeta.x500Name(),
//					SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(caCert.getPublicKey().getEn)
					new SubjectPublicKeyInfo(ASN1Sequence.getInstance(caCert.getPublicKey().getEncoded()))
					);
			List<GeneralName> lsan = new ArrayList<GeneralName>();
			for(String s : csrmeta.sans()) {
				lsan.add(new GeneralName(GeneralName.dNSName,s));
			}
			GeneralName[] sans = new GeneralName[lsan.size()];
			lsan.toArray(sans);

		    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
		    xcb		.addExtension(Extension.basicConstraints,
                    	false, new BasicConstraints(false))
		            .addExtension(Extension.keyUsage,
		                true, new KeyUsage(KeyUsage.digitalSignature
		                                 | KeyUsage.keyEncipherment))
		            .addExtension(Extension.extendedKeyUsage,
		                          true, new ExtendedKeyUsage(ASN_WebUsage))

                    .addExtension(Extension.authorityKeyIdentifier,
		                          false, extUtils.createAuthorityKeyIdentifier(caCert))
		            .addExtension(Extension.subjectKeyIdentifier,
		                          false, extUtils.createSubjectKeyIdentifier(caCert.getPublicKey()))
		            .addExtension(Extension.subjectAlternativeName,
		            		false, new GeneralNames(sans))
		                                           ;
	
			x509 = new JcaX509CertificateConverter().getCertificate(
					xcb.build(BCFactory.contentSigner(caKey)));
		} catch (GeneralSecurityException|OperatorCreationException e) {
			throw new CertException(e);
		} finally {
			tt.done();
		}
		return x509;
	}
144621
public static PKIXCertPathBuilderResult verifyChain(X509Certificate testCert, X509Certificate... additionalCerts) {
        try {
            // Check for self-signed certificate
            if (isSelfSigned(testCert)) {
                throw new RuntimeException("The certificate is self-signed.  Nothing to verify.");
            }

            // Prepare a set of all certificates
            // chain builder must have all certs, including cert to validate
            // http://stackoverflow.com/a/10788392
            Set<X509Certificate> certs = new HashSet<X509Certificate>();
            certs.add(testCert);
            certs.addAll(Arrays.asList(additionalCerts));

            // Attempt to build the certification chain and verify it
            // Create the selector that specifies the starting certificate
            X509CertSelector selector = new X509CertSelector();
            selector.setCertificate(testCert);

            // Create the trust anchors (set of root CA certificates)
            Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
            for (X509Certificate cert : additionalCerts) {
                if (isSelfSigned(cert)) {
                    trustAnchors.add(new TrustAnchor(cert, null));
                }
            }

            // Configure the PKIX certificate builder
            PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);
            pkixParams.setRevocationEnabled(false);
            pkixParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs), BC));

            // Build and verify the certification chain
            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BC);
            PKIXCertPathBuilderResult verifiedCertChain = (PKIXCertPathBuilderResult) builder.build(pkixParams);

            // The chain is built and verified
            return verifiedCertChain;
        } catch (CertPathBuilderException e) {
            throw new RuntimeException("Error building certification path: " + testCert.getSubjectX500Principal(), e);
        } catch (Exception e) {
            throw new RuntimeException("Error verifying the certificate: " + testCert.getSubjectX500Principal(), e);
        }
    }
183613
@Override
	public void engineSetCertificateEntry(String alias, Certificate certificate)
			throws KeyStoreException {

		if (!(certificate instanceof X509Certificate)) {
			throw new KeyStoreException(
					"Certificate must be instance of X509Certificate");
		}
		File file;
		ResourceTrustAnchor trustAnchor = getCertificateEntry(alias);
		if (trustAnchor != null) {
			file = trustAnchor.getFile();
		} else {
			file = new File(defaultDirectory, alias);
		}
		X509Certificate x509Cert = (X509Certificate) certificate;
		try {
			if(!inMemoryOnly){
				writeCertificate(x509Cert, file);
			}
			ResourceTrustAnchor anchor = new ResourceTrustAnchor(inMemoryOnly,
					new GlobusResource(file.getAbsolutePath()), new TrustAnchor(x509Cert,
							null));
			this.aliasObjectMap.put(alias, anchor);
			this.certFilenameMap.put(x509Cert, alias);
		} catch (ResourceStoreException e) {
			throw new KeyStoreException(e);
		} catch (IOException e) {
			throw new KeyStoreException(e);
		} catch (CertificateEncodingException e) {
			throw new KeyStoreException(e);
		}
	}
243673
public static void writeCertificate(
            OutputStream out,
            X509Certificate cert)
            throws IOException, CertificateEncodingException {
        PEMUtil.writeBase64(out,
                "-----BEGIN CERTIFICATE-----",
                Base64.encode(cert.getEncoded()),
                "-----END CERTIFICATE-----");
    }
479842
private void buildReverse(List<List<Vertex>> adjacencyList,
                              LinkedList<X509Certificate> certPathList)
        throws GeneralSecurityException, IOException
    {
        if (debug != null) {
            debug.println("SunCertPathBuilder.buildReverse()...");
            debug.println("SunCertPathBuilder.buildReverse() InitialPolicies: "
                + buildParams.initialPolicies());
        }

        ReverseState currentState = new ReverseState();
        /* Initialize adjacency list */
        adjacencyList.clear();
        adjacencyList.add(new LinkedList<Vertex>());

        /*
         * Perform a search using each trust anchor, until a valid
         * path is found
         */
        Iterator<TrustAnchor> iter = buildParams.trustAnchors().iterator();
        while (iter.hasNext()) {
            TrustAnchor anchor = iter.next();

            /* check if anchor satisfies target constraints */
            if (anchorIsTarget(anchor, buildParams.targetCertConstraints())) {
                this.trustAnchor = anchor;
                this.pathCompleted = true;
                this.finalPublicKey = anchor.getTrustedCert().getPublicKey();
                break;
            }

            // skip anchor if it contains a DSA key with no DSA params
            X509Certificate trustedCert = anchor.getTrustedCert();
            PublicKey pubKey = trustedCert != null ? trustedCert.getPublicKey()
                                                   : anchor.getCAPublicKey();

            if (PKIX.isDSAPublicKeyWithoutParams(pubKey)) {
                continue;
            }

            /* Initialize current state */
            currentState.initState(buildParams);
            currentState.updateState(anchor, buildParams);

            currentState.algorithmChecker = new AlgorithmChecker(anchor);
            currentState.untrustedChecker = new UntrustedChecker();
            try {
                depthFirstSearchReverse(null, currentState,
                                        new ReverseBuilder(buildParams),
                                        adjacencyList, certPathList);
            } catch (GeneralSecurityException | IOException e) {
                // continue on error if more anchors to try
                if (iter.hasNext())
                    continue;
                else
                    throw e;
            }

            // break out of loop if search is successful
            if (pathCompleted) {
                break;
            }
        }

        if (debug != null) {
            debug.println("SunCertPathBuilder.buildReverse() returned from "
                + "depthFirstSearchReverse()");
            debug.println("SunCertPathBuilder.buildReverse() "
                + "certPathList.size: " + certPathList.size());
        }
    }
104978
public static void verify(X509Certificate cert, PublicKey key,
            Provider sigProvider) throws CertificateException,
            NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        cert.verify(key, sigProvider);
    }
807256
@Override
    public void loadCACertificatesAsBytes(Collection<byte[]> certificatesBytes) throws CryptoException {
        if (certificatesBytes == null || certificatesBytes.size() == 0) {
            throw new CryptoException("List of CA certificates is empty. Nothing to load.");
        }

        ArrayList<Certificate> certList = new ArrayList<>();
        for (byte[] certBytes : certificatesBytes) {
            certList.add(bytesToCertificate(certBytes));
        }
        loadCACertificates(certList);

    }
1172201
public static synchronized X509CertificatePair generateCertificatePair
            (byte[] encoded) throws CertificateException {
        Object key = new Cache.EqualByteArray(encoded);
        X509CertificatePair pair = cache.get(key);
        if (pair != null) {
            return pair;
        }
        pair = new X509CertificatePair(encoded);
        key = new Cache.EqualByteArray(pair.encoded);
        cache.put(key, pair);
        return pair;
    }
139984
@SneakyThrows
    public X509Certificate loadCert(String certLocation) {
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        Resource certRes = resourceLoader.getResource(certLocation);
        X509Certificate cert = (X509Certificate) cf.generateCertificate(certRes.getInputStream());
        return cert;
    }
478607
public static SSLSocketFactory getTrustAllCertSslSocketFactory() {
    try {
      TrustManager[] trustAllCerts = new TrustManager[]{
          new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
              return new X509Certificate[]{};
            }
          }
      };

      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

      return sslContext.getSocketFactory();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
1079358
private X509Certificate createCACert(PublicKey publicKey, PrivateKey privateKey) throws Exception {

        // signers name
        X500Name issuerName = new X500Name("CN=www.mockserver.com, O=MockServer, L=London, ST=England, C=UK");

        // subjects name - the same as we are self signed.
        X500Name subjectName = issuerName;

        // serial
        BigInteger serial = BigInteger.valueOf(new Random().nextInt(Integer.MAX_VALUE));

        // create the certificate - version 3
        X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, NOT_BEFORE, NOT_AFTER, subjectName, publicKey);
        builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

        KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
        builder.addExtension(Extension.keyUsage, false, usage);

        ASN1EncodableVector purposes = new ASN1EncodableVector();
        purposes.add(KeyPurposeId.id_kp_serverAuth);
        purposes.add(KeyPurposeId.id_kp_clientAuth);
        purposes.add(KeyPurposeId.anyExtendedKeyUsage);
        builder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));

        X509Certificate cert = signCertificate(builder, privateKey);
        cert.checkValidity(new Date());
        cert.verify(publicKey);

        return cert;
    }
556738
function(c, signature) {
    if(c.session.certificateRequest !== null &&
      c.session.clientCertificate !== null) {
      // create certificate verify message
      tls.queue(c, tls.createRecord(c, {
        type: tls.ContentType.handshake,
        data: tls.createCertificateVerify(c, signature)
      }));
    }

    // create change cipher spec message
    tls.queue(c, tls.createRecord(c, {
      type: tls.ContentType.change_cipher_spec,
      data: tls.createChangeCipherSpec()
    }));

    // create pending state
    c.state.pending = tls.createConnectionState(c);

    // change current write state to pending write state
    c.state.current.write = c.state.pending.write;

    // create finished message
    tls.queue(c, tls.createRecord(c, {
      type: tls.ContentType.handshake,
      data: tls.createFinished(c)
    }));

    // expect a server ChangeCipherSpec message next
    c.expect = SCC;

    // send records
    tls.flush(c);

    // continue
    c.process();
  }
830644
@Override
  public X509Certificate getClientCertificate()
    throws java.security.cert.CertificateException
  {
    TempBuffer tb = TempBuffer.create();
    byte []buffer = tb.buffer();
    int len = getClientCertificate(_socketFd, buffer, 0, buffer.length);
    X509Certificate cert = null;

    if (len > 0 && len < buffer.length) {
      try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream is = new ByteArrayInputStream(buffer, 0, len);
        cert = (X509Certificate) cf.generateCertificate(is);
        is.close();
      } catch (IOException e) {
        return null;
      }
    }

    TempBuffer.free(tb);
    tb = null;

    return cert;
  }
5076
@Override
	protected void engineInit(KeyStore keyStore) throws KeyStoreException {
		try {
			this
					.engineInit(new CertPathTrustManagerParameters(
							new X509ProxyCertPathParameters(keyStore, null,
									null, false)));
		} catch (InvalidAlgorithmParameterException e) {
			throw new KeyStoreException(e);
		}
	}