Java HTTPS客户端证书身份验证

时间:2009-11-03 08:51:40

标签: java ssl https client-certificates

我是HTTPS/SSL/TLS的新手,我对使用证书进行身份验证时客户应该提供的内容感到有些困惑。

我正在编写一个Java客户端,需要对特定的POST执行简单的URL数据。那部分工作正常,唯一的问题是它应该在HTTPS上完成。 HTTPS部分相当容易处理(使用HTTPclient或使用Java的内置HTTPS支持),但我仍然坚持使用客户端证书进行身份验证。我注意到这里已经有一个非常类似的问题了,我还没有用我的代码试过(很快就会这么做)。我当前的问题是 - 无论我做什么 - Java客户端永远不会发送证书(我可以使用PCAP转储检查)。

我想知道在使用证书进行身份验证时,客户端应该向服务器提供什么样的内容(特别是对于Java - 如果这一点很重要)?这是JKS个文件,还是PKCS#12?什么应该在他们身上;只是客户端证书,还是密钥?如果是这样,哪个关键?所有不同类型的文件,证书类型等都存在很多混淆。

正如我之前所说的那样,我是HTTPS/SSL/TLS的新手,所以我也会欣赏一些背景信息(不一定是一篇文章;我会接受好文章的链接)。< / p>

8 个答案:

答案 0 :(得分:217)

最后设法解决了所有问题,所以我会回答我自己的问题。这些是我用来管理以解决我的特定问题的设置/文件;

客户端密钥库是包含

PKCS#12格式文件
  1. 客户的公开证书(在此实例中由自签名CA签名)
  2. 客户的私人密钥
  3. 为了生成它,我使用了OpenSSL的pkcs12命令,例如;

    openssl pkcs12 -export -in client.crt -inkey client.key -out client.p12 -name "Whatever"
    

    提示:确保您获得最新的OpenSSL,版本0.9.8h,因为它似乎遭受了一个不允许您正确生成PKCS的错误#12个文件。

    当服务器明确请求客户端进行身份验证时,Java客户端将使用此PKCS#12文件向服务器提供客户端证书。有关客户端证书身份验证协议实际工作原理的概述,请参阅Wikipedia article on TLS。(此外,我们还需要了解客户端私钥的原因)。

    客户端的信任库是一个直接的 JKS格式文件,其中包含 root 中间CA证书。这些CA证书将确定允许您与哪些端点通信,在这种情况下,它将允许您的客户端连接到任何服务器提供由其中一个信任库CA签署的证书。

    要生成它,您可以使用标准Java keytool,例如;

    keytool -genkey -dname "cn=CLIENT" -alias truststorekey -keyalg RSA -keystore ./client-truststore.jks -keypass whatever -storepass whatever
    keytool -import -keystore ./client-truststore.jks -file myca.crt -alias myca
    

    使用此信任库,您的客户端将尝试与提供由myca.crt标识的CA签名的证书的所有服务器进行完整的SSL握手。

    以上文件仅供客户使用。如果要设置服务器,服务器还需要自己的密钥和信任库文件。可以在this website上找到为Java客户端和服务器(使用Tomcat)设置完整工作示例的一个很好的演练。

    <强>问题/备注/提示

    1. 客户端证书身份验证只能由服务器强制执行。
    2. 重要!)当服务器请求客户端证书(作为TLS握手的一部分)时,它还将提供可信CA的列表作为证书请求的一部分。当您希望提交用于身份验证的客户端证书由其中一个CA签名时,它将根本不会显示(在我看来,这是奇怪的行为,但我确信这是一个原因)。这是我的问题的主要原因,因为另一方没有正确配置他们的服务器以接受我的自签名客户端证书,并且我们认为问题是因为我没有在请求中正确提供客户端证书。
    3. 获取Wireshark。它具有出色的SSL / HTTPS数据包分析功能,可以帮助您调试和发现问题。它与-Djavax.net.debug=ssl类似,但如果您对Java SSL调试输出感到不舒服,则更易于理解,并且(可以说)更容易理解。
    4. 完全可以使用Apache httpclient库。如果要使用httpclient,只需使用HTTPS等效项替换目标URL,并添加以下JVM参数(对于任何其他客户端都是相同的,无论您要使用哪个库通过HTTP / HTTPS发送/接收数据) :

      -Djavax.net.debug=ssl
      -Djavax.net.ssl.keyStoreType=pkcs12
      -Djavax.net.ssl.keyStore=client.p12
      -Djavax.net.ssl.keyStorePassword=whatever
      -Djavax.net.ssl.trustStoreType=jks
      -Djavax.net.ssl.trustStore=client-truststore.jks
      -Djavax.net.ssl.trustStorePassword=whatever

答案 1 :(得分:30)

他们JKS文件只是证书和密钥对的容器。 在客户端身份验证方案中,密钥的各个部分将位于此处:

  • 客户端的商店将包含客户端的私有和公共密钥对。它被称为密钥库
  • 服务器的商店将包含客户的公开键。它被称为信任库

信任库和密钥库的分离不是强制性的,但建议使用。它们可以是相同的物理文件。

要设置两个商店的文件系统位置,请使用以下系统属性:

-Djavax.net.ssl.keyStore=clientsidestore.jks

并在服务器上:

-Djavax.net.ssl.trustStore=serversidestore.jks

要将客户端的证书(公钥)导出到文件,以便将其复制到服务器,请使用

keytool -export -alias MYKEY -file publicclientkey.cer -store clientsidestore.jks

要将客户端的公钥导入服务器的密钥库,请使用(如上所述,已经由服务器管理员完成)

keytool -import -file publicclientkey.cer -store serversidestore.jks

答案 2 :(得分:9)

Maven pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>some.examples</groupId>
    <artifactId>sslcliauth</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>sslcliauth</name>
    <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.4</version>
        </dependency>
    </dependencies>
</project>

Java代码:

package some.examples;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.InputStreamEntity;

public class SSLCliAuthExample {

private static final Logger LOG = Logger.getLogger(SSLCliAuthExample.class.getName());

private static final String CA_KEYSTORE_TYPE = KeyStore.getDefaultType(); //"JKS";
private static final String CA_KEYSTORE_PATH = "./cacert.jks";
private static final String CA_KEYSTORE_PASS = "changeit";

private static final String CLIENT_KEYSTORE_TYPE = "PKCS12";
private static final String CLIENT_KEYSTORE_PATH = "./client.p12";
private static final String CLIENT_KEYSTORE_PASS = "changeit";

public static void main(String[] args) throws Exception {
    requestTimestamp();
}

public final static void requestTimestamp() throws Exception {
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(
            createSslCustomContext(),
            new String[]{"TLSv1"}, // Allow TLSv1 protocol only
            null,
            SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    try (CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(csf).build()) {
        HttpPost req = new HttpPost("https://changeit.com/changeit");
        req.setConfig(configureRequest());
        HttpEntity ent = new InputStreamEntity(new FileInputStream("./bytes.bin"));
        req.setEntity(ent);
        try (CloseableHttpResponse response = httpclient.execute(req)) {
            HttpEntity entity = response.getEntity();
            LOG.log(Level.INFO, "*** Reponse status: {0}", response.getStatusLine());
            EntityUtils.consume(entity);
            LOG.log(Level.INFO, "*** Response entity: {0}", entity.toString());
        }
    }
}

public static RequestConfig configureRequest() {
    HttpHost proxy = new HttpHost("changeit.local", 8080, "http");
    RequestConfig config = RequestConfig.custom()
            .setProxy(proxy)
            .build();
    return config;
}

public static SSLContext createSslCustomContext() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    // Trusted CA keystore
    KeyStore tks = KeyStore.getInstance(CA_KEYSTORE_TYPE);
    tks.load(new FileInputStream(CA_KEYSTORE_PATH), CA_KEYSTORE_PASS.toCharArray());

    // Client keystore
    KeyStore cks = KeyStore.getInstance(CLIENT_KEYSTORE_TYPE);
    cks.load(new FileInputStream(CLIENT_KEYSTORE_PATH), CLIENT_KEYSTORE_PASS.toCharArray());

    SSLContext sslcontext = SSLContexts.custom()
            //.loadTrustMaterial(tks, new TrustSelfSignedStrategy()) // use it to customize
            .loadKeyMaterial(cks, CLIENT_KEYSTORE_PASS.toCharArray()) // load client certificate
            .build();
    return sslcontext;
}

}

答案 3 :(得分:7)

对于那些只想设置双向身份验证(服务器和客户端证书)的人来说,这两个链接的组合可以帮助您:

双向身份验证设置:

https://linuxconfig.org/apache-web-server-ssl-authentication

您不需要使用他们提到的openssl配置文件;只需使用

  • $ openssl genrsa -des3 -out ca.key 4096

  • $ openssl req -new -x509 -days 365 -key ca.key -out ca.crt

生成您自己的CA证书,然后通过以下方式生成并签署服务器和客户端密钥:

  • $ openssl genrsa -des3 -out server.key 4096

  • $ openssl req -new -key server.key -out server.csr

  • $ openssl x509 -req -days 365 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 100 -out server.crt

  • $ openssl genrsa -des3 -out client.key 4096

  • $ openssl req -new -key client.key -out client.csr

  • $ openssl x509 -req -days 365 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 101 -out client.crt

其余部分请按照链接中的步骤操作。管理Chrome的证书与上面提到的firefox示例相同。

接下来,通过以下方式设置服务器:

https://www.digitalocean.com/community/tutorials/how-to-create-a-ssl-certificate-on-apache-for-ubuntu-14-04

请注意,您已经创建了服务器.crt和.key,因此您不必再执行该步骤了。

答案 4 :(得分:2)

有一种更好的方法,而不是必须手动导航到https:// url,知道在哪种浏览器中单击哪个按钮,知道在何处以及如何保存“证书”文件以及最后知道keytool的魔咒在本地安装。

只需执行以下操作:

  1. 将下面的代码保存到InstallCert.java
  2. 打开命令行并执行:javac InstallCert.java
  3. 运行方式:java InstallCert <host>[:port] [passphrase](端口和密码是可选的)

这是InstallCert的代码,请注意标题中的年份,将需要修改Java“更高”版本的某些部分:

/*
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.*;
import java.net.URL;

import java.security.*;
import java.security.cert.*;

import javax.net.ssl.*;

public class InstallCert {

    public static void main(String[] args) throws Exception {
  String host;
  int port;
  char[] passphrase;
  if ((args.length == 1) || (args.length == 2)) {
      String[] c = args[0].split(":");
      host = c[0];
      port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
      String p = (args.length == 1) ? "changeit" : args[1];
      passphrase = p.toCharArray();
  } else {
      System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
      return;
  }

  File file = new File("jssecacerts");
  if (file.isFile() == false) {
      char SEP = File.separatorChar;
      File dir = new File(System.getProperty("java.home") + SEP
        + "lib" + SEP + "security");
      file = new File(dir, "jssecacerts");
      if (file.isFile() == false) {
    file = new File(dir, "cacerts");
      }
  }
  System.out.println("Loading KeyStore " + file + "...");
  InputStream in = new FileInputStream(file);
  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(in, passphrase);
  in.close();

  SSLContext context = SSLContext.getInstance("TLS");
  TrustManagerFactory tmf =
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  tmf.init(ks);
  X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
  SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
  context.init(null, new TrustManager[] {tm}, null);
  SSLSocketFactory factory = context.getSocketFactory();

  System.out.println("Opening connection to " + host + ":" + port + "...");
  SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
  socket.setSoTimeout(10000);
  try {
      System.out.println("Starting SSL handshake...");
      socket.startHandshake();
      socket.close();
      System.out.println();
      System.out.println("No errors, certificate is already trusted");
  } catch (SSLException e) {
      System.out.println();
      e.printStackTrace(System.out);
  }

  X509Certificate[] chain = tm.chain;
  if (chain == null) {
      System.out.println("Could not obtain server certificate chain");
      return;
  }

  BufferedReader reader =
    new BufferedReader(new InputStreamReader(System.in));

  System.out.println();
  System.out.println("Server sent " + chain.length + " certificate(s):");
  System.out.println();
  MessageDigest sha1 = MessageDigest.getInstance("SHA1");
  MessageDigest md5 = MessageDigest.getInstance("MD5");
  for (int i = 0; i < chain.length; i++) {
      X509Certificate cert = chain[i];
      System.out.println
        (" " + (i + 1) + " Subject " + cert.getSubjectDN());
      System.out.println("   Issuer  " + cert.getIssuerDN());
      sha1.update(cert.getEncoded());
      System.out.println("   sha1    " + toHexString(sha1.digest()));
      md5.update(cert.getEncoded());
      System.out.println("   md5     " + toHexString(md5.digest()));
      System.out.println();
  }

  System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
  String line = reader.readLine().trim();
  int k;
  try {
      k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
  } catch (NumberFormatException e) {
      System.out.println("KeyStore not changed");
      return;
  }

  X509Certificate cert = chain[k];
  String alias = host + "-" + (k + 1);
  ks.setCertificateEntry(alias, cert);

  OutputStream out = new FileOutputStream("jssecacerts");
  ks.store(out, passphrase);
  out.close();

  System.out.println();
  System.out.println(cert);
  System.out.println();
  System.out.println
    ("Added certificate to keystore 'jssecacerts' using alias '"
    + alias + "'");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
  StringBuilder sb = new StringBuilder(bytes.length * 3);
  for (int b : bytes) {
      b &= 0xff;
      sb.append(HEXDIGITS[b >> 4]);
      sb.append(HEXDIGITS[b & 15]);
      sb.append(' ');
  }
  return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

  private final X509TrustManager tm;
  private X509Certificate[] chain;

  SavingTrustManager(X509TrustManager tm) {
      this.tm = tm;
  }

  public X509Certificate[] getAcceptedIssuers() {
      throw new UnsupportedOperationException();
  }

  public void checkClientTrusted(X509Certificate[] chain, String authType)
    throws CertificateException {
      throw new UnsupportedOperationException();
  }

  public void checkServerTrusted(X509Certificate[] chain, String authType)
    throws CertificateException {
      this.chain = chain;
      tm.checkServerTrusted(chain, authType);
  }
    }

} 

答案 5 :(得分:1)

给出一个同时带有证书和私钥的p12文件(例如,由openssl生成),以下代码会将其用于特定的HttpsURLConnection:

insert into table_2 (col1, col2, col3, error_value)
select  
    col1, col2, col3, stuff(
        concat(
        ',' + case when col1 is null then 'col1' end, -- will be null if col1 contains a value
        ',' + case when col2 is null then 'col2' end, -- will be null if col2 contains a value
        ',' + case when col3 is null then 'col3' end, -- will be null if col3 contains a value
        ' is null'), 1, 1, '')
from table_1
where col1 is null or col2 is null or col3 is null

insert into table_2 (col1, col2, col3, col4) select col1, col2, col3, CONCAT( IIF(col1 is null, 'col1 ', ''), IIF(col2 is null, 'col2 ', ''), IIF(col3 is null, 'col3 ', ''), ' is null' ) from table_1 where col1 is null or col2 is null or col3 is null 需要花费一些时间进行初始化,因此您可能需要对其进行缓存。

答案 6 :(得分:0)

我认为这里的修复是密钥库类型,pkcs12(pfx)总是有私钥,而JKS类型可以没有私钥。除非您在代码中指定或通过浏览器选择证书,否则服务器无法知道它代表另一端的客户端。

答案 7 :(得分:0)

我已通过Spring Boot使用双向SSL(客户端和服务器证书)连接到银行。因此,请在此处描述我的所有步骤,希望对您有所帮助(我找到了最简单的解决方案):

  1. 生成证书请求:

    • 生成私钥:

      openssl genrsa -des3 -passout pass:MY_PASSWORD -out user.key 2048
      
    • 生成证书请求:

      openssl req -new -key user.key -out user.csr -passin pass:MY_PASSWORD
      

    保留user.key(和密码)并将证书请求user.csr发送到银行以获取我的证书

  2. 接收2个证书:我的客户根证书clientId.crt和银行根证书:bank.crt

  3. 创建Java密钥库(输入密钥密码并设置密钥库密码):

    openssl pkcs12 -export -in clientId.crt -inkey user.key -out keystore.p12 -name clientId -CAfile ca.crt -caname root
    

    不要关注输出:unable to write 'random state'。 Java PKCS12 keystore.p12已创建。

  4. 添加到密钥库bank.crt中(为简单起见,我使用了一个密钥库):

    keytool -import -alias banktestca -file banktestca.crt -keystore keystore.p12 -storepass javaops
    

    通过以下方式检查密钥库证书:

    keytool -list -keystore keystore.p12
    
  5. 准备好使用Java代码:)我已经将Spring Boot RestTemplate与添加org.apache.httpcomponents.httpcore依赖项一起使用:

    @Bean("sslRestTemplate")
    public RestTemplate sslRestTemplate() throws Exception {
      char[] storePassword = appProperties.getSslStorePassword().toCharArray();
      URL keyStore = new URL(appProperties.getSslStore());
    
      SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(keyStore, storePassword)
      // use storePassword twice (with key password do not work)!!
            .loadKeyMaterial(keyStore, storePassword, storePassword) 
            .build();
    
      // Solve "Certificate doesn't match any of the subject alternative names"
      SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    
      CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
      HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
      RestTemplate restTemplate = new RestTemplate(factory);
      // restTemplate.setMessageConverters(List.of(new Jaxb2RootElementHttpMessageConverter()));
      return restTemplate;
    }