use*_*730 59 java ssl keystore truststore
我正在用Java编写一个应用程序,它通过HTTPS连接到两个Web服务器.一个通过默认的信任链获得证书,另一个使用自签名证书.当然,连接到第一台服务器是开箱即用的,而在我使用该服务器的证书创建一个trustStore之前,使用自签名证书连接到服务器不起作用.但是,与默认可信服务器的连接不再起作用,因为显然我创建自己的默认trustStore会被忽略.
我找到的一个解决方案是将证书从默认的trustStore添加到我自己的.但是,我不喜欢这个解决方案,因为它需要我继续管理那个trustStore.(我不能假设这些证书在可预见的未来仍然是静态的,对吧?)
除此之外,我发现了两个有着类似问题的5岁线程:
他们都深入到Java SSL基础架构.我希望到现在有一个更方便的解决方案,我可以在我的代码的安全审查中轻松解释.
Bru*_*uno 70
您可以使用与我之前的答案中提到的类似模式(针对不同的问题).
实质上,获取默认信任管理器,创建第二个使用您自己的信任库的信任管理器.将它们都包装在一个自定义信任管理器实现中,该实现将代理调用两者(当一个失败时返回另一个).
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// Using null here initialises the TMF with the default trust store.
tmf.init((KeyStore) null);
// Get hold of the default trust manager
X509TrustManager defaultTm = null;
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
defaultTm = (X509TrustManager) tm;
break;
}
}
FileInputStream myKeys = new FileInputStream("truststore.jks");
// Do the same with your trust store this time
// Adapt how you load the keystore to your needs
KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
myTrustStore.load(myKeys, "password".toCharArray());
myKeys.close();
tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(myTrustStore);
// Get hold of the default trust manager
X509TrustManager myTm = null;
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
myTm = (X509TrustManager) tm;
break;
}
}
// Wrap it in your own class.
final X509TrustManager finalDefaultTm = defaultTm;
final X509TrustManager finalMyTm = myTm;
X509TrustManager customTm = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
// If you're planning to use client-cert auth,
// merge results from "defaultTm" and "myTm".
return finalDefaultTm.getAcceptedIssuers();
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
try {
finalMyTm.checkServerTrusted(chain, authType);
} catch (CertificateException e) {
// This will throw another CertificateException if this fails too.
finalDefaultTm.checkServerTrusted(chain, authType);
}
}
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
// If you're planning to use client-cert auth,
// do the same as checking the server.
finalDefaultTm.checkClientTrusted(chain, authType);
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { customTm }, null);
// You don't have to set this as the default context,
// it depends on the library you're using.
SSLContext.setDefault(sslContext);
Run Code Online (Sandbox Code Playgroud)
您不必将该上下文设置为默认上下文.您如何使用它取决于您正在使用的客户端库(以及从哪里获取其套接字工厂).
这就是说,原则上,你总是需要根据需要更新信任库.Java 7 JSSE参考指南有一个关于此的"重要说明",现在降级为同一指南的第8版中的"注释":
JDK在java-home/lib/security/cacerts文件中附带有限数量的受信任根证书.如keytool参考页中所述,如果您将此文件用作信任库,则您有责任维护(即添加和删除)此文件中包含的证书.
根据您联系的服务器的证书配置,您可能需要添加其他根证书.从相应的供应商处获取所需的特定根证书.
您可以通过调用TrustManagerFactory.init((KeyStore)null)并获取其X509Certificates来检索默认信任存储。将此与您自己的证书结合起来。您可以从加载自签名证书.jks或.p12文件,KeyStore.load也可以加载一个.crt(或.cer通过)文件CertificateFactory。
这是一些演示代码,说明了这一点。如果您使用浏览器从 stackoverflow.com 下载证书,则可以运行该代码。如果您注释掉添加加载的证书和默认值,代码将获得SSLHandshakeException,但如果您保留其中之一,它将返回状态代码 200。
import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.*;
import java.security.cert.*;
public class HttpsWithCustomCertificateDemo {
public static void main(String[] args) throws Exception {
// Create a new trust store, use getDefaultType for .jks files or "pkcs12" for .p12 files
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
// Create a new trust store, use getDefaultType for .jks files or "pkcs12" for .p12 files
trustStore.load(null, null);
// If you comment out the following, the request will fail
trustStore.setCertificateEntry(
"stackoverflow",
// To test, download the certificate from stackoverflow.com with your browser
loadCertificate(new File("stackoverflow.crt"))
);
// Uncomment to following to add the installed certificates to the keystore as well
//addDefaultRootCaCertificates(trustStore);
SSLSocketFactory sslSocketFactory = createSslSocketFactory(trustStore);
URL url = new URL("https://stackoverflow.com/");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// Alternatively, to use the sslSocketFactory for all Http requests, uncomment
//HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
conn.setSSLSocketFactory(sslSocketFactory);
System.out.println(conn.getResponseCode());
}
private static SSLSocketFactory createSslSocketFactory(KeyStore trustStore) throws GeneralSecurityException {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManagers, null);
return sslContext.getSocketFactory();
}
private static X509Certificate loadCertificate(File certificateFile) throws IOException, CertificateException {
try (FileInputStream inputStream = new FileInputStream(certificateFile)) {
return (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(inputStream);
}
}
private static void addDefaultRootCaCertificates(KeyStore trustStore) throws GeneralSecurityException {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// Loads default Root CA certificates (generally, from JAVA_HOME/lib/cacerts)
trustManagerFactory.init((KeyStore)null);
for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
if (trustManager instanceof X509TrustManager) {
for (X509Certificate acceptedIssuer : ((X509TrustManager) trustManager).getAcceptedIssuers()) {
trustStore.setCertificateEntry(acceptedIssuer.getSubjectDN().getName(), acceptedIssuer);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是布鲁诺答案的更清晰版本
public void configureTrustStore() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException,
CertificateException, IOException {
X509TrustManager jreTrustManager = getJreTrustManager();
X509TrustManager myTrustManager = getMyTrustManager();
X509TrustManager mergedTrustManager = createMergedTrustManager(jreTrustManager, myTrustManager);
setSystemTrustManager(mergedTrustManager);
}
private X509TrustManager getJreTrustManager() throws NoSuchAlgorithmException, KeyStoreException {
return findDefaultTrustManager(null);
}
private X509TrustManager getMyTrustManager() throws FileNotFoundException, KeyStoreException, IOException,
NoSuchAlgorithmException, CertificateException {
// Adapt to load your keystore
try (FileInputStream myKeys = new FileInputStream("truststore.jks")) {
KeyStore myTrustStore = KeyStore.getInstance("jks");
myTrustStore.load(myKeys, "password".toCharArray());
return findDefaultTrustManager(myTrustStore);
}
}
private X509TrustManager findDefaultTrustManager(KeyStore keyStore)
throws NoSuchAlgorithmException, KeyStoreException {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore); // If keyStore is null, tmf will be initialized with the default trust store
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
return (X509TrustManager) tm;
}
}
return null;
}
private X509TrustManager createMergedTrustManager(X509TrustManager jreTrustManager,
X509TrustManager customTrustManager) {
return new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
// If you're planning to use client-cert auth,
// merge results from "defaultTm" and "myTm".
return jreTrustManager.getAcceptedIssuers();
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
customTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException e) {
// This will throw another CertificateException if this fails too.
jreTrustManager.checkServerTrusted(chain, authType);
}
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// If you're planning to use client-cert auth,
// do the same as checking the server.
jreTrustManager.checkClientTrusted(chain, authType);
}
};
}
private void setSystemTrustManager(X509TrustManager mergedTrustManager)
throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { mergedTrustManager }, null);
// You don't have to set this as the default context,
// it depends on the library you're using.
SSLContext.setDefault(sslContext);
}
Run Code Online (Sandbox Code Playgroud)
也许我回答这个问题已经晚了 6 年,但它可能对其他开发人员也有帮助。我还遇到了加载默认信任库和我自己的自定义信任库的相同挑战。在为多个项目使用相同的自定义解决方案后,我认为创建一个库并将其公开以回馈社区会很方便。请看这里:Github - SSLContext-Kickstart
用法:
import nl.altindag.sslcontext.SSLFactory;
import javax.net.ssl.SSLContext;
import java.security.cert.X509Certificate;
import java.util.List;
public class App {
public static void main(String[] args) {
String trustStorePath = ...;
char[] password = "password".toCharArray();
SSLFactory sslFactory = SSLFactory.builder()
.withDefaultTrustMaterial()
.withTrustMaterial(trustStorePath, password)
.build();
SSLContext sslContext = sslFactory.getSslContext();
List<X509Certificate> trustedCertificates = sslFactory.getTrustedCertificates();
}
}
Run Code Online (Sandbox Code Playgroud)
我不太确定我是否应该在这里发布它,因为它也可以被视为一种推广“我的库”的方式,但我认为它可能对面临相同挑战的开发人员有所帮助。
| 归档时间: |
|
| 查看次数: |
50764 次 |
| 最近记录: |