Java Code Examples for javax.net.ssl.X509KeyManager#getPrivateKey()

The following examples show how to use javax.net.ssl.X509KeyManager#getPrivateKey() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClientCertificateHandlerTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void handlesCombinedKeyAndCert() throws IOException {
  Files.write(
      clientKeyPath, (SAMPLE_CLIENT_CERT + "\n" + SAMPLE_CLIENT_KEY).getBytes(Charsets.UTF_8));

  String[] keyLines = SAMPLE_CLIENT_KEY.split("\n");
  byte[] expectedPrivateKey =
      Base64.getDecoder()
          .decode(String.join("", Arrays.copyOfRange(keyLines, 1, keyLines.length - 1)));
  String expectedPublic = "CN=Client, OU=Buck, O=\"Facebook, Inc.\", L=Seattle, ST=WA, C=US";

  Optional<ClientCertificateHandler> handler =
      ClientCertificateHandler.fromConfiguration(config_required);

  X509KeyManager keyManager = handler.get().getHandshakeCertificates().keyManager();
  String alias = keyManager.getClientAliases("RSA", null)[0];
  PrivateKey privateKey = keyManager.getPrivateKey(alias);
  String subjectName = keyManager.getCertificateChain(alias)[0].getSubjectDN().getName();

  Assert.assertArrayEquals(expectedPrivateKey, privateKey.getEncoded());
  Assert.assertEquals(expectedPublic, subjectName);
  Assert.assertFalse(handler.get().getHostnameVerifier().isPresent());
}
 
Example 2
Source File: FileTrustStoreSslSocketFactory.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
public PrivateKey getPrivateKey(final String alias) {
    for (final X509KeyManager keyManager : keyManagers) {
        final PrivateKey privateKey = keyManager.getPrivateKey(alias);
        if (privateKey != null) {
            return privateKey;
        }
    }
    return null;
}
 
Example 3
Source File: SSLKeyManager.java    From PADListener with GNU General Public License v2.0 5 votes vote down vote up
public synchronized PrivateKey getPrivateKey(String alias) {
    String[] parts = alias.split(SEP, 2);
    String description = parts[0];
    alias = parts[1];
    X509KeyManager km = _managers.get(description);
    return km.getPrivateKey(alias);
}
 
Example 4
Source File: CompositeX509KeyManager.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the first non-null private key associated with the given alias, or {@code null} if
 * the alias can't be found.
 */
@Override
public @Nullable PrivateKey getPrivateKey(String alias){
	for (List<X509KeyManager> keyManagers : keyManagers.values()) {
		for (X509KeyManager x509KeyManager : keyManagers) {
			PrivateKey privateKey = x509KeyManager.getPrivateKey(alias);
			if (privateKey != null) {
				return privateKey;
			}
		}
	}
	return null;
}
 
Example 5
Source File: OpenSSLContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
public void addCertificate(SSLHostConfigCertificate certificate) throws Exception {
    // Load Server key and certificate
    if (certificate.getCertificateFile() != null) {
        // Set certificate
        SSLContext.setCertificate(ctx,
                SSLHostConfig.adjustRelativePath(certificate.getCertificateFile()),
                SSLHostConfig.adjustRelativePath(certificate.getCertificateKeyFile()),
                certificate.getCertificateKeyPassword(), getCertificateIndex(certificate));
        // Set certificate chain file
        SSLContext.setCertificateChainFile(ctx,
                SSLHostConfig.adjustRelativePath(certificate.getCertificateChainFile()), false);
        // Set revocation
        SSLContext.setCARevocation(ctx,
                SSLHostConfig.adjustRelativePath(
                        sslHostConfig.getCertificateRevocationListFile()),
                SSLHostConfig.adjustRelativePath(
                        sslHostConfig.getCertificateRevocationListPath()));
    } else {
        String alias = certificate.getCertificateKeyAlias();
        X509KeyManager x509KeyManager = certificate.getCertificateKeyManager();
        if (alias == null) {
            alias = "tomcat";
        }
        X509Certificate[] chain = x509KeyManager.getCertificateChain(alias);
        if (chain == null) {
            alias = findAlias(x509KeyManager, certificate);
            chain = x509KeyManager.getCertificateChain(alias);
        }
        PrivateKey key = x509KeyManager.getPrivateKey(alias);
        StringBuilder sb = new StringBuilder(BEGIN_KEY);
        String encoded = BASE64_ENCODER.encodeToString(key.getEncoded());
        if (encoded.endsWith("\n")) {
            encoded = encoded.substring(0, encoded.length() - 1);
        }
        sb.append(encoded);
        sb.append(END_KEY);
        SSLContext.setCertificateRaw(ctx, chain[0].getEncoded(),
                sb.toString().getBytes(StandardCharsets.US_ASCII),
                getCertificateIndex(certificate));
        for (int i = 1; i < chain.length; i++) {
            SSLContext.addChainCertificateRaw(ctx, chain[i].getEncoded());
        }
    }
}
 
Example 6
Source File: ClientCertificateHandlerTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void handlesCombinedKeyAndCertAndIntermediateCA() throws IOException {
  Path identityPath = temporaryPaths.newFile("client.pem");
  Path identityPathReverse = temporaryPaths.newFile("client_reverse.pem");
  Files.write(
      identityPath,
      (SAMPLE_CLIENT_INTERMEDIATE_CERT
              + "\n"
              + SAMPLE_CA_INTERMEDIATE_CERT
              + "\n"
              + SAMPLE_CLIENT_INTERMEDIATE_KEY)
          .getBytes(Charsets.UTF_8));
  Files.write(
      identityPathReverse,
      (SAMPLE_CLIENT_INTERMEDIATE_KEY
              + "\n"
              + SAMPLE_CLIENT_INTERMEDIATE_CERT
              + "\n"
              + SAMPLE_CA_INTERMEDIATE_CERT)
          .getBytes(Charsets.UTF_8));

  String[] keyLines = SAMPLE_CLIENT_INTERMEDIATE_KEY.split("\n");
  byte[] expectedPrivateKey =
      Base64.getDecoder()
          .decode(String.join("", Arrays.copyOfRange(keyLines, 1, keyLines.length - 1)));

  Path[] testPaths = {identityPath, identityPathReverse};
  for (Path testPath : testPaths) {
    ArtifactCacheBuckConfig config =
        ArtifactCacheBuckConfigTest.createFromText(
            "[cache]",
            "http_client_tls_key = " + testPath.toString(),
            "http_client_tls_cert = " + testPath.toString(),
            "http_client_tls_cert_required = yes");

    String expectedPublic =
        "CN=Client Intermediate, OU=Buck, O=\"Facebook, Inc.\", L=Seattle, ST=WA, C=US";
    String expectedIntermediateCa =
        "CN=Test CA Intermediate, OU=Buck, O=\"Facebook, Inc.\", L=Seattle, ST=WA, C=US";

    Optional<ClientCertificateHandler> handler =
        ClientCertificateHandler.fromConfiguration(config);

    X509KeyManager keyManager = handler.get().getHandshakeCertificates().keyManager();
    String alias = keyManager.getClientAliases("RSA", null)[0];
    PrivateKey privateKey = keyManager.getPrivateKey(alias);
    String subjectName = keyManager.getCertificateChain(alias)[0].getSubjectDN().getName();
    String intermediateCaSubjectName =
        keyManager.getCertificateChain(alias)[1].getSubjectDN().getName();

    Assert.assertArrayEquals(expectedPrivateKey, privateKey.getEncoded());
    Assert.assertEquals(expectedPublic, subjectName);
    Assert.assertEquals(expectedIntermediateCa, intermediateCaSubjectName);
    Assert.assertFalse(handler.get().getHostnameVerifier().isPresent());
  }
}