我已经看到了这个问题:Need to do a GET&POST HTTPS Request using a .cer certificate
我的情况完全不同:
可以使用Java(vanilla,或使用任何库)发出HTTPS请求,信任服务器证书并提供客户端证书,而不使用密钥库但使用普通证书?
我有两种X.509格式的证书,而且我不想在密钥库中拥有所有证书。
答案 0 :(得分:1)
这是一个粗略的例子。表示X509KeyManager装饰器。
EXT: The PHP file extension
FCPATH: Path to the front controller (this file) (root of CI)
SELF: The name of THIS file (index.php)
BASEPATH: Path to the system folder
APPPATH: The path to the “application” folder
答案 1 :(得分:0)
如果您真的不想创建新的密钥库文件,那么可以使用KeyStore API在内存中创建并直接加载证书。
InputStream is = new FileInputStream("somecert.cer");
// You could get a resource as a stream instead.
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate caCert = (X509Certificate)cf.generateCertificate(is);
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null); // You don't need the KeyStore instance to come from a file.
ks.setCertificateEntry("caCert", caCert);
tmf.init(ks);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
或者,如果您想避免修改默认的cacerts文件,那么您需要实现自己的TrustManager。但是,TrustManager需要加载密钥库,因此您可以创建仅导入证书的新密钥库文件。
keytool -import -alias ca -file somecert.cer -keystore truststore.jks -storepass changeit
并使用以下代码段来加载密钥库文件。
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);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);