java https客户端证书身份验证

0ejtzxu1  于 2021-07-05  发布在  Java
关注(0)|答案(9)|浏览(527)

我是个新手 HTTPS/SSL/TLS 我对客户端在使用证书进行身份验证时到底应该显示什么有点困惑。
我正在编写一个java客户机,它需要做一个简单的 POST 将数据传输到特定的 URL . 那部分很好用,唯一的问题是应该重做一遍 HTTPS . 这个 HTTPS 零件很容易处理(或 HTTPclient 或者使用java的内置 HTTPS 支持),但我一直坚持使用客户端证书进行身份验证。我注意到这里已经有一个非常类似的问题,我还没有用我的代码尝试过这个问题(很快就会尝试)。我目前的问题是,无论我做什么,java客户机都不会发送证书(我可以用 PCAP 转储)。
我想知道在使用证书进行身份验证时,客户端到底应该向服务器呈现什么(特别是对于java—如果这很重要的话)?这是一个 JKS 文件,或 PKCS#12 ? 里面应该有什么;只是客户端证书,还是密钥?如果是,哪把钥匙?对于所有不同类型的文件、证书类型等等,都有相当多的混淆。
正如我之前所说,我是新手 HTTPS/SSL/TLS 所以我也会很感激一些背景资料(不一定是一篇论文;我会满足于好文章的链接)。

tp5buhyn

tp5buhyn1#

有一种比手动导航到https://url ,知道在哪个浏览器中单击哪个按钮,知道在哪里以及如何保存“证书”文件,最后知道keytool在本地安装它的魔法咒语。
就这么做吧:
将下面的代码保存到installcert.java
打开命令行并执行: javac InstallCert.java 跑步方式: 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);
  }
    }

}
lx0bsm1f

lx0bsm1f2#

我用双向ssl(客户机和服务器证书)和spring boot连接到银行。因此,请在这里描述我的所有步骤,希望它能帮助某些人(最简单的工作解决方案,我发现):
生成证书请求:
生成私钥:

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证书:我的客户端根证书 clientId.crt 和银行根证书: bank.crt 创建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 创建。
添加到密钥库 bank.crt (为了简单起见,我使用了一个密钥库):

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

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

keytool -list -keystore keystore.p12

java代码准备就绪:)我已经使用了springboot RestTemplate 带add 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;
}
0dxa2lsx

0dxa2lsx3#

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

z9gpfhce

z9gpfhce4#

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
qvtsj1bj

qvtsj1bj5#

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;
}

}
1rhkuytd

1rhkuytd6#

其他答案显示了如何全局配置客户端证书。但是,如果您希望以编程方式定义一个特定连接的客户机密钥,而不是在jvm上运行的每个应用程序中全局定义它,那么您可以像这样配置自己的sslcontext:

String keyPassphrase = "";

KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream("cert-key-pair.pfx"), keyPassphrase.toCharArray());

SSLContext sslContext = SSLContexts.custom()
        .loadKeyMaterial(keyStore, null)
        .build();

HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
HttpResponse response = httpClient.execute(new HttpGet("https://example.com"));
ohfgkhjo

ohfgkhjo7#

终于解决了所有的问题,所以我来回答我自己的问题。这些是我用来解决特定问题的设置/文件;
客户机的密钥库是一个pkcs#12格式的文件,包含
客户端的公共证书(在本例中由自签名ca签名)
客户端的私钥
为了生成它,我使用了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关于tls的文章,了解客户端证书身份验证协议的实际工作原理(也解释了为什么这里需要客户端的私钥)。
客户机的信任库是一个直接的jks格式文件,包含根证书或中间ca证书。这些ca证书将决定允许您与哪些端点通信,在这种情况下,它将允许您的客户端连接到提供由信任库的ca之一签名的证书的服务器。
例如,要生成它,可以使用标准的javakeytool;

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

使用此信任库,您的客户机将尝试与提供由所标识的ca签名的证书的所有服务器进行完整的ssl握手 myca.crt .
以上文件仅供客户使用。当您还想设置服务器时,服务器需要自己的密钥和信任库文件。在这个网站上可以找到为java客户机和服务器(使用tomcat)设置一个完全工作的示例的一个很好的演练。
问题/备注/提示
客户端证书身份验证只能由服务器强制执行。
(重要!)当服务器请求客户机证书(作为tls握手的一部分)时,它还将作为证书请求的一部分提供受信任ca的列表。当您希望呈现用于身份验证的客户端证书没有由这些ca之一签名时,它根本不会呈现(在我看来,这是一种奇怪的行为,但我确信这是有原因的)。这是我的问题的主要原因,因为另一方没有正确地配置他们的服务器以接受我的自签名客户端证书,并且我们假设问题出在我这边,因为没有在请求中正确地提供客户端证书。
抓住线鲨。它有很好的ssl/https数据包分析,将是一个巨大的帮助调试和发现问题。类似于 -Djavax.net.debug=ssl 但是,如果您对javassl调试输出感到不舒服,那么它的结构更加结构化并且(可以说)更容易解释。
完全可以使用apachehttpclient库。如果您想使用httpclient,只需将目标url替换为等价的https,并添加以下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
6gpjuf90

6gpjuf908#

对于那些只想设置双向身份验证(服务器和客户端证书)的用户,这两个链接的组合将使您达到以下目的:
双向身份验证设置:
https://linuxconfig.org/apache-web-server-ssl-authentication
您不需要使用他们提到的openssl配置文件;只是使用
$openssl genrsa-des3-输出ca.key 4096
$openssl req-new-x509-365天-key ca.key-out ca.crt
生成您自己的ca证书,然后通过以下方式生成并签署服务器和客户端密钥:
$openssl genrsa-des3-out服务器密钥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 \u serial 100-out server.crt

$openssl genrsa-des3-out客户端.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 \u 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
请注意,您已经创建了server.crt和.key,因此不必再执行该步骤。

zi8p0yeb

zi8p0yeb9#

给定一个包含证书和私钥的p12文件(例如,由openssl生成),以下代码将其用于特定的httpsurlconnection:

KeyStore keyStore = KeyStore.getInstance("pkcs12");
    keyStore.load(new FileInputStream(keyStorePath), keystorePassword.toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keystorePassword.toCharArray());
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(kmf.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = ctx.getSocketFactory();

    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setSSLSocketFactory(sslSocketFactory);

这个 SSLContext 初始化需要一些时间,因此您可能需要缓存它。

相关问题