Java Code Examples for java.security.KeyStore.setCertificateEntry()

The following are Jave code examples for showing how to use setCertificateEntry() of the java.security.KeyStore class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: MQTT-Essentials-A-Lightweight-IoT-Protocol   File: SecurityHelper.java   View Source Code Vote up 7 votes
private static KeyManagerFactory createKeyManagerFactory(
	final String clientCertificateFileName, final String clientKeyFileName, final String clientKeyPassword) 
	throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException
{
	// Creates a key manager factory
	// Load and create the client certificate
	final X509Certificate clientCertificate = createX509CertificateFromFile(clientCertificateFileName);	
	// Load the private client key
	final PrivateKey privateKey = createPrivateKeyFromPemFile(clientKeyFileName);
	// Client key and certificate are sent to server
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
	keyStore.load(null, null);
	keyStore.setCertificateEntry("certificate", clientCertificate);
	keyStore.setKeyEntry("private-key", privateKey, 
		clientKeyPassword.toCharArray(),
		new Certificate[] { clientCertificate });
	final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	keyManagerFactory.init(keyStore, clientKeyPassword.toCharArray());
	
	return keyManagerFactory;
}
 
Example 2
Project: openjdk-jdk10   File: ComodoHacker.java   View Source Code Vote up 6 votes
private static X509TrustManager getTrustManager() throws Exception {
    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trusted cert
    try (ByteArrayInputStream is =
            new ByteArrayInputStream(trustedCertStr.getBytes())) {
        Certificate trustedCert = cf.generateCertificate(is);
        ks.setCertificateEntry("RSA Export Signer", trustedCert);
    }

    // create the trust manager
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);

    return (X509TrustManager)tmf.getTrustManagers()[0];
}
 
Example 3
Project: BlogBookApp   File: MyWebService.java   View Source Code Vote up 6 votes
private SSLSocketFactory addCertificate(InputStream inputStream) throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException, KeyManagementException {
    // loading CAs from an InputStream
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate ca;
    try {
        ca = cf.generateCertificate(inputStream);
    } finally {
        inputStream.close();
    }

    // creating a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // creating a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // creating an SSLSocketFactory that uses our TrustManager
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, tmf.getTrustManagers(), null);

    return sslContext.getSocketFactory();
}
 
Example 4
Project: outland   File: CertificateLoader.java   View Source Code Vote up 6 votes
private void installCertificates(Path path, KeyStore keyStore)
    throws IOException, CertificateException {
  CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

  try (DirectoryStream<Path> paths = Files.newDirectoryStream(path, "*.{crt,pem}")) {
    for (Path certPath : paths) {
      logger.info("installing cert from path {}", certPath.toRealPath());
      if (Files.isRegularFile(certPath)) {
        try (InputStream inputStream = Files.newInputStream(certPath)) {
          Certificate cert = certificateFactory.generateCertificate(inputStream);
          String alias = certPath.getFileName().toString();
          keyStore.setCertificateEntry(alias, cert);
          logger.info("ok, installed cert with alias {} from path {}", alias,
              certPath.toRealPath());
        } catch (Exception e) {
          logger.warn("error, skipping cert, path {} {}", certPath.toRealPath(), e.getMessage());
        }
      } else {
        logger.info("skipping cert, not a regular file {}", certPath.toRealPath());
      }
    }
  }
}
 
Example 5
Project: iot-edge-greengrass   File: CertPemClientCredentials.java   View Source Code Vote up 5 votes
private KeyManagerFactory createAndInitKeyManagerFactory() throws Exception {
  X509Certificate certHolder = certificateConverter.getCertificate((X509CertificateHolder) readPEMFile(cert));

  Object keyObject = readPEMFile(privateKey);

  char[] passwordCharArray = "".toCharArray();
  if (!StringUtils.isEmpty(password)) {
    passwordCharArray = password.toCharArray();
  }

  JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC");

  KeyPair key;
  if (keyObject instanceof PEMEncryptedKeyPair) {
    PEMDecryptorProvider provider = new JcePEMDecryptorProviderBuilder().build(passwordCharArray);
    key = keyConverter.getKeyPair(((PEMEncryptedKeyPair) keyObject).decryptKeyPair(provider));
  } else {
    key = keyConverter.getKeyPair((PEMKeyPair) keyObject);
  }

  KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
  clientKeyStore.load(null, null);
  clientKeyStore.setCertificateEntry("cert", certHolder);
  clientKeyStore.setKeyEntry("private-key", key.getPrivate(), passwordCharArray, new Certificate[] { certHolder });

  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(clientKeyStore, passwordCharArray);
  return keyManagerFactory;
}
 
Example 6
Project: ditb   File: KeyStoreTestUtil.java   View Source Code Vote up 5 votes
public static void createTrustStore(String filename,
                                    String password, String alias,
                                    Certificate cert)
  throws GeneralSecurityException, IOException {
  KeyStore ks = createEmptyKeyStore();
  ks.setCertificateEntry(alias, cert);
  saveKeyStore(ks, filename, password);
}
 
Example 7
Project: common-spider   File: HttpsUtil.java   View Source Code Vote up 5 votes
private static X509TrustManager trustManagerForCertificates(InputStream in)
        throws GeneralSecurityException {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
    if (certificates.isEmpty()) {
        throw new IllegalArgumentException("expected non-empty set of trusted certificates");
    }

    // Put the certificates a key store.
    char[] password = "password".toCharArray(); // Any password will work.
    KeyStore keyStore = newEmptyKeyStore(password);
    int index = 0;
    for (Certificate certificate : certificates) {
        String certificateAlias = Integer.toString(index++);
        keyStore.setCertificateEntry(certificateAlias, certificate);
    }

    // Use it to build an X509 trust manager.
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
        throw new IllegalStateException("Unexpected default trust managers:"
                + Arrays.toString(trustManagers));
    }
    return (X509TrustManager) trustManagers[0];
}
 
Example 8
Project: GitHub   File: CustomTrust.java   View Source Code Vote up 5 votes
/**
 * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
 * certificates have not been signed by these certificates will fail with a {@code
 * SSLHandshakeException}.
 *
 * <p>This can be used to replace the host platform's built-in trusted certificates with a custom
 * set. This is useful in development where certificate authority-trusted certificates aren't
 * available. Or in production, to avoid reliance on third-party certificate authorities.
 *
 * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using
 * the host platform's built-in trust store.
 *
 * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
 *
 * <p>Relying on your own trusted certificates limits your server team's ability to update their
 * TLS certificates. By installing a specific set of trusted certificates, you take on additional
 * operational complexity and limit your ability to migrate between certificate authorities. Do
 * not use custom trusted certificates in production without the blessing of your server's TLS
 * administrator.
 */
private X509TrustManager trustManagerForCertificates(InputStream in)
    throws GeneralSecurityException {
  CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
  Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
  if (certificates.isEmpty()) {
    throw new IllegalArgumentException("expected non-empty set of trusted certificates");
  }

  // Put the certificates a key store.
  char[] password = "password".toCharArray(); // Any password will work.
  KeyStore keyStore = newEmptyKeyStore(password);
  int index = 0;
  for (Certificate certificate : certificates) {
    String certificateAlias = Integer.toString(index++);
    keyStore.setCertificateEntry(certificateAlias, certificate);
  }

  // Use it to build an X509 trust manager.
  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
      KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(keyStore, password);
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
      TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(keyStore);
  TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:"
        + Arrays.toString(trustManagers));
  }
  return (X509TrustManager) trustManagers[0];
}
 
Example 9
Project: hadoop-oss   File: KeyStoreTestUtil.java   View Source Code Vote up 5 votes
public static void createTrustStore(String filename,
    String password, String alias,
    Certificate cert)
    throws GeneralSecurityException, IOException {
  KeyStore ks = createEmptyKeyStore();
  ks.setCertificateEntry(alias, cert);
  saveKeyStore(ks, filename, password);
}
 
Example 10
Project: hadoop-oss   File: KeyStoreTestUtil.java   View Source Code Vote up 5 votes
public static <T extends Certificate> void createTrustStore(
    String filename, String password, Map<String, T> certs)
    throws GeneralSecurityException, IOException {
  KeyStore ks = createEmptyKeyStore();
  for (Map.Entry<String, T> cert : certs.entrySet()) {
    ks.setCertificateEntry(cert.getKey(), cert.getValue());
  }
  saveKeyStore(ks, filename, password);
}
 
Example 11
Project: in-store-api-java-sdk   File: NetworkUtilities.java   View Source Code Vote up 5 votes
public static OkHttpClient.Builder getClient(SatispayContext satispayContext) {
    OkHttpClient.Builder okHttpClientBuilder;
    okHttpClientBuilder = new OkHttpClient.Builder();

    // ==> the SSL context is build only in environments different from PROD / STAGING, where the server cert is self signed
    String serverCert = satispayContext.getServerCert();
    if (serverCert != null) {
        try {
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore;
            keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", CryptoUtils.certificateX509(serverCert));

            String trustManagerDefaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerDefaultAlgorithm);
            trustManagerFactory.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            okHttpClientBuilder.sslSocketFactory(sslSocketFactory);
        } catch (Exception e) {
            ProtoLogger.error("!!! Error generating TLS context !!!");
        }
    }
    okHttpClientBuilder.connectTimeout(10, TimeUnit.SECONDS);
    okHttpClientBuilder.writeTimeout(10, TimeUnit.SECONDS);
    okHttpClientBuilder.readTimeout(30, TimeUnit.SECONDS);
    return okHttpClientBuilder;
}
 
Example 12
Project: xitk   File: ImportCertCmd.java   View Source Code Vote up 5 votes
@Override
protected Object execute0() throws Exception {
    File realKsFile = new File(IoUtil.expandFilepath(ksFile));
    KeyStore ks = KeyStore.getInstance(ksType);
    char[] password = readPasswordIfNotSet(ksPwd);

    Set<String> aliases = new HashSet<>(10);
    if (realKsFile.exists()) {
        FileInputStream inStream = new FileInputStream(realKsFile);
        try {
            ks.load(inStream, password);
        } finally {
            inStream.close();
        }

        Enumeration<String> strs = ks.aliases();
        while (strs.hasMoreElements()) {
            aliases.add(strs.nextElement());
        }
    } else {
        ks.load(null);
    }

    for (String certFile : certFiles) {
        X509Certificate cert = X509Util.parseCert(certFile);
        String baseAlias = X509Util.getCommonName(cert.getSubjectX500Principal());
        String alias = baseAlias;
        int idx = 2;
        while (aliases.contains(alias)) {
            alias = baseAlias + "-" + (idx++);
        }
        ks.setCertificateEntry(alias, cert);
        aliases.add(alias);
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
    ks.store(bout, password);
    saveVerbose("saved keystore to file", realKsFile, bout.toByteArray());
    return null;
}
 
Example 13
Project: okhttpUtil   File: CustomTrustParams.java   View Source Code Vote up 5 votes
/**
 * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
 * certificates have not been signed by these certificates will fail with a {@code
 * SSLHandshakeException}.
 *
 * <p>This can be used to replace the host platform's built-in trusted certificates with a custom
 * set. This is useful in development where certificate authority-trusted certificates aren't
 * available. Or in production, to avoid reliance on third-party certificate authorities.
 *
 * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using
 * the host platform's built-in trust store.
 *
 * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
 *
 * <p>Relying on your own trusted certificates limits your server team's ability to update their
 * TLS certificates. By installing a specific set of trusted certificates, you take on additional
 * operational complexity and limit your ability to migrate between certificate authorities. Do
 * not use custom trusted certificates in production without the blessing of your server's TLS
 * administrator.
 */
private X509TrustManager trustManagerForCertificates(InputStream in)
    throws GeneralSecurityException {
  CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
  Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
  if (certificates.isEmpty()) {
    throw new IllegalArgumentException("expected non-empty set of trusted certificates");
  }

  // Put the certificates a key store.
  char[] password = "password".toCharArray(); // Any password will work.
  KeyStore keyStore = newEmptyKeyStore(password);
  int index = 0;
  for (Certificate certificate : certificates) {
    String certificateAlias = Integer.toString(index++);
    keyStore.setCertificateEntry(certificateAlias, certificate);
  }

  // Use it to build an X509 trust manager.
  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
      KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(keyStore, password);
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
      TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(keyStore);
  TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:"
        + Arrays.toString(trustManagers));
  }
  return (X509TrustManager) trustManagers[0];
}
 
Example 14
Project: BTNotifierAndroid   File: SslUtils.java   View Source Code Vote up 5 votes
private void trustCertificate(Certificate cert, String deviceLabel) throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException {
    KeyStore ts = getKeyStore();

    Log.i(TAG, "Adding certificate ID " + deviceLabel + " to Trust store (" + trustStorePath + "): " + cert);
    ts.setCertificateEntry(deviceLabel, cert);

    ts.store(new FileOutputStream(trustStorePath), null);
}
 
Example 15
Project: jdk8u-jdk   File: RSAExport.java   View Source Code Vote up 4 votes
private SSLContext getSSLContext(boolean authnRequired) throws Exception {
    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    ByteArrayInputStream is =
                new ByteArrayInputStream(trusedCertStr.getBytes());
    Certificate trustedCert = cf.generateCertificate(is);

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trusted cert
    ks.setCertificateEntry("RSA Export Signer", trustedCert);

    if (authnRequired) {
        // generate the private key.
        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
                                        new BigInteger(modulus),
                                        new BigInteger(privateExponent));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(serverCertStr.getBytes());
        Certificate serverCert = cf.generateCertificate(is);

        Certificate[] chain = new Certificate[2];
        chain[0] = serverCert;
        chain[1] = trustedCert;

        // import the key entry.
        ks.setKeyEntry("RSA Export", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");
    if (authnRequired) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 16
Project: openjdk-jdk10   File: DHEKeySizing.java   View Source Code Vote up 4 votes
private SSLContext getSSLContext() throws Exception {

        // generate certificate from cert string
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        // create a key store
        KeyStore ts = KeyStore.getInstance("JKS");
        KeyStore ks = KeyStore.getInstance("JKS");
        ts.load(null, null);
        ks.load(null, null);

        // import the trused cert
        ByteArrayInputStream is =
                    new ByteArrayInputStream(trustedCertStr.getBytes());
        Certificate trusedCert = cf.generateCertificate(is);
        is.close();
        ts.setCertificateEntry("rsa-trusted-2048", trusedCert);

        // generate the private key.
        String keySpecStr = targetPrivateKey;
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(keySpecStr));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey = (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        Certificate[] chain = new Certificate[1];
        chain[0] = trusedCert;

        // import the key entry.
        ks.setKeyEntry("rsa-key-2048", priKey, passphrase, chain);

        // create SSL context
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ts);

        SSLContext sslCtx = SSLContext.getInstance("TLSv1");
        sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        return sslCtx;
    }
 
Example 17
Project: jdk8u-jdk   File: MD2InTrustAnchor.java   View Source Code Vote up 4 votes
private static SSLContext generateSSLContext(String trustedCertStr,
        String keyCertStr, String keySpecStr) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    Certificate trusedCert = null;
    ByteArrayInputStream is = null;
    if (trustedCertStr != null) {
        is = new ByteArrayInputStream(trustedCertStr.getBytes());
        trusedCert = cf.generateCertificate(is);
        is.close();

        ks.setCertificateEntry("RSA Export Signer", trusedCert);
    }

    if (keyCertStr != null) {
        // generate the private key.
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(keySpecStr));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        // It's not allowed to send MD2 signed certificate to peer,
        // even it may be a trusted certificate. Then we will not
        // place the trusted certficate in the chain.
        Certificate[] chain = new Certificate[1];
        chain[0] = keyCert;

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance(tlsProtocol);
    if (keyCertStr != null && !keyCertStr.isEmpty()) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        ks = null;
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 18
Project: framework   File: SSLUtil.java   View Source Code Vote up 4 votes
/**
 * Performs Certificate Chain Validation on provided certificates. The method verifies if the client certificates provided are generated from root certificates
 * trusted by application.
 *
 * @param clientCerts Collection of X509Certificates provided in request
 * @param trustCerts  Collection of X509Certificates trusted by application
 * @param authType    Auth Type for Certificate
 * @return true if client and server are chained together, false otherwise
 * @throws PayPalRESTException
 */
public static boolean validateCertificateChain(Collection<X509Certificate> clientCerts, Collection<X509Certificate> trustCerts, String authType) throws PayPalRESTException {
	TrustManager trustManagers[];
	X509Certificate[] clientChain;
	try {

		clientChain = clientCerts.toArray(new X509Certificate[0]);
		List<X509Certificate> list = Arrays.asList(clientChain);
		clientChain = list.toArray(new X509Certificate[0]);

		// Create a Keystore and load the Root CA Cert
		KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
		keyStore.load(null, "".toCharArray());

		// Iterate through each certificate and add to keystore
		int i = 0;
		for (Iterator<X509Certificate> payPalCertificate = trustCerts.iterator(); payPalCertificate.hasNext(); ) {
			X509Certificate x509Certificate = (X509Certificate) payPalCertificate.next();
			keyStore.setCertificateEntry("paypalCert" + i, x509Certificate);
			i++;
		}

		// Create TrustManager
		TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		trustManagerFactory.init(keyStore);
		trustManagers = trustManagerFactory.getTrustManagers();

	} catch (Exception ex) {
		throw new PayPalRESTException(ex);
	}

	// For Each TrustManager of type X509
	for (TrustManager trustManager : trustManagers) {
		if (trustManager instanceof X509TrustManager) {
			X509TrustManager pkixTrustManager = (X509TrustManager) trustManager;
			// Check the trust manager if server is trusted
			try {
				pkixTrustManager.checkClientTrusted(clientChain, (authType == null || authType == "") ? "RSA" : authType);
				// Checks that the certificate is currently valid. It is if the current date and time are within the validity period given in the certificate.
				for (X509Certificate cert : clientChain) {
					cert.checkValidity();
					// Check for CN name matching
					String dn = cert.getSubjectX500Principal().getName();
					String[] tokens = dn.split(",");
					boolean hasPaypalCn = false;

					for (String token : tokens) {
						if (token.startsWith("CN=messageverificationcerts") && token.endsWith(".paypal.com")) {
							hasPaypalCn = true;
						}
					}

					if (!hasPaypalCn) {
						throw new PayPalRESTException("CN of client certificate does not match with trusted CN");
					}
				}
				// If everything looks good, return true
				return true;
			} catch (CertificateException e) {
				throw new PayPalRESTException(e);
			}
		}
	}


	return false;

}
 
Example 19
Project: jdk8u-jdk   File: SunX509ExtendedTM.java   View Source Code Vote up 4 votes
private static SSLContext getSSLContext(String trusedCertStr,
        String keyCertStr, byte[] modulus,
        byte[] privateExponent, char[] passphrase) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    ByteArrayInputStream is =
                new ByteArrayInputStream(trusedCertStr.getBytes());
    Certificate trusedCert = cf.generateCertificate(is);
    is.close();

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    ks.setCertificateEntry("RSA Export Signer", trusedCert);

    if (keyCertStr != null) {
        // generate the private key.
        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
                                        new BigInteger(modulus),
                                        new BigInteger(privateExponent));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = new Certificate[2];
        chain[0] = keyCert;
        chain[1] = trusedCert;

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf =
            TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

    TrustManager tms[] = tmf.getTrustManagers();
    if (tms == null || tms.length == 0) {
        throw new Exception("unexpected trust manager implementation");
    } else {
       if (!(tms[0] instanceof X509ExtendedTrustManager)) {
        throw new Exception("unexpected trust manager implementation: "
                            + tms[0].getClass().getCanonicalName());
       }
    }


    SSLContext ctx = SSLContext.getInstance("TLS");

    if (keyCertStr != null) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 20
Project: jdk8u-jdk   File: SignatureAlgorithms.java   View Source Code Vote up 4 votes
private static SSLContext generateSSLContext(String trustedCertStr,
        String[] keyCertStrs, String[] keySpecStrs) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    Certificate trusedCert = null;
    ByteArrayInputStream is = null;
    if (trustedCertStr != null) {
        is = new ByteArrayInputStream(trustedCertStr.getBytes());
        trusedCert = cf.generateCertificate(is);
        is.close();

        ks.setCertificateEntry("DSA Signer", trusedCert);
    }

    if (keyCertStrs != null && keyCertStrs.length != 0) {
        for (int i = 0; i < keyCertStrs.length; i++) {
            String keyCertStr = keyCertStrs[i];
            String keySpecStr = keySpecStrs[i];

            // generate the private key.
            PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                            new BASE64Decoder().decodeBuffer(keySpecStr));
            KeyFactory kf = KeyFactory.getInstance("DSA");
            DSAPrivateKey priKey =
                    (DSAPrivateKey)kf.generatePrivate(priKeySpec);

            // generate certificate chain
            is = new ByteArrayInputStream(keyCertStr.getBytes());
            Certificate keyCert = cf.generateCertificate(is);
            is.close();

            Certificate[] chain = null;
            if (trusedCert != null) {
                chain = new Certificate[2];
                chain[0] = keyCert;
                chain[1] = trusedCert;
            } else {
                chain = new Certificate[1];
                chain[0] = keyCert;
            }

            // import the key entry.
            ks.setKeyEntry("DSA Entry " + i, priKey, passphrase, chain);
        }
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");
    if (keyCertStrs != null && keyCertStrs.length != 0) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        ks = null;
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}