Certyfikaty klientów Java przez HTTPS / SSL
Używam Javy 6 i próbuję utworzyć HttpsURLConnection
na zdalnym serwerze, używając certyfikatu klienta.
Serwer używa własnoręcznie podpisanego certyfikatu głównego i wymaga przedstawienia certyfikatu klienta zabezpieczonego hasłem. Dodałem certyfikat główny serwera i certyfikat klienta do domyślnego klucza java, który znalazłem w /System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home/lib/security/cacerts
(OSX 10.5).
Nazwa pliku keystore sugeruje, że certyfikat klienta nie powinien tam wchodzić?
W każdym razie, dodanie certyfikatu głównego do tego sklepu rozwiązało infamous javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed' problem.
Jednak teraz utknąłem na tym, jak korzystać z certyfikatu klienta. Próbowałem dwóch podejść i Żadne z nich nigdzie mnie nie zaprowadzi.
Pierwszy i preferowany, spróbuj:
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
URL url = new URL("https://somehost.dk:3049");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sslsocketfactory);
InputStream inputstream = conn.getInputStream();
// The last line fails, and gives:
// javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
Próbowałem pominąć klasę HttpsURLConnection (nie jest to idealne rozwiązanie, ponieważ chcę rozmawiać HTTP z serwerem), a zamiast tego zrobić to:
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("somehost.dk", 3049);
InputStream inputstream = sslsocket.getInputStream();
// do anything with the inputstream results in:
// java.net.SocketTimeoutException: Read timed out
Nie jestem nawet pewien, czy certyfikat klienta jest tutaj problemem.
8 answers
W końcu rozwiązałem;). Mam mocną podpowiedź tutaj (Gandalfs odpowiedział trochę na to, jak również). Brakujące linki były (głównie) pierwszym z poniższych parametrów i do pewnego stopnia przeoczyłem różnicę między keystore i truststore.
Certyfikat serwera z podpisem własnym musi zostać zaimportowany do truststore:
Keytool-import-alias gridserver-plik gridserver.crt-storepass $PASS-keystore gridserver.keystore
Te właściwości muszą być ustawione (albo w wierszu poleceń, albo w kodzie):
-Djavax.net.ssl.keyStoreType=pkcs12
-Djavax.net.ssl.trustStoreType=jks
-Djavax.net.ssl.keyStore=clientcertificate.p12
-Djavax.net.ssl.trustStore=gridserver.keystore
-Djavax.net.debug=ssl # very verbose debug
-Djavax.net.ssl.keyStorePassword=$PASS
-Djavax.net.ssl.trustStorePassword=$PASS
Działający przykładowy kod:
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
URL url = new URL("https://gridserver:3049/cgi-bin/ls.py");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sslsocketfactory);
InputStream inputstream = conn.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String string = null;
while ((string = bufferedreader.readLine()) != null) {
System.out.println("Received " + string);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-12 10:19:12
Chociaż nie jest to zalecane, możesz również wyłączyć walidację certyfikatu SSL alltogether:
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
public class SSLTool {
public static void disableCertificateValidation() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}};
// Ignore differences between given hostname and certificate hostname
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) { return true; }
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Exception e) {}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-25 08:31:43
Czy Ustawiłeś właściwości systemu KeyStore i/lub TrustStore?
java -Djavax.net.ssl.keyStore=pathToKeystore -Djavax.net.ssl.keyStorePassword=123456
Lub z kodem
System.setProperty("javax.net.ssl.keyStore", pathToKeyStore);
To samo z javax. net. ssl. trustStore
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-17 22:42:20
Jeśli masz do czynienia z wywołaniem usługi internetowej za pomocą frameworka Axis, istnieje o wiele prostsza odpowiedź. Jeśli wszystko zależy od tego, aby twój klient mógł wywołać usługę internetową SSL i zignorować błędy certyfikatu SSL, po prostu umieść to oświadczenie przed wywołaniem jakichkolwiek usług internetowych:
System.setProperty("axis.socketSecureFactory",
"org.apache.axis.components.net.SunFakeTrustSocketFactory");
Stosuje się zwykle zastrzeżenia dotyczące tego, że jest to bardzo zła rzecz w środowisku produkcyjnym.
Znalazłem to na Axis wiki .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-07 21:42:54
Dla mnie to działa przy użyciu Apache HttpComponents ~ HttpClient 4.x:
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
try {
keyStore.load(instream, "helloworld".toCharArray());
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, "helloworld".toCharArray())
//.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) //custom trust store
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
CloseableHttpClient httpclient = HttpClients.custom()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
.setSSLSocketFactory(sslsf)
.build();
try {
HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
Plik P12 zawiera certyfikat klienta i klucz prywatny klienta, utworzony za pomocą BouncyCastle:
public static byte[] convertPEMToPKCS12(final String keyFile, final String cerFile,
final String password)
throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException,
NoSuchProviderException
{
// Get the private key
FileReader reader = new FileReader(keyFile);
PEMParser pem = new PEMParser(reader);
PEMKeyPair pemKeyPair = ((PEMKeyPair)pem.readObject());
JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter().setProvider("BC");
KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
PrivateKey key = keyPair.getPrivate();
pem.close();
reader.close();
// Get the certificate
reader = new FileReader(cerFile);
pem = new PEMParser(reader);
X509CertificateHolder certHolder = (X509CertificateHolder) pem.readObject();
java.security.cert.Certificate x509Certificate =
new JcaX509CertificateConverter().setProvider("BC")
.getCertificate(certHolder);
pem.close();
reader.close();
// Put them into a PKCS12 keystore and write it to a byte[]
ByteArrayOutputStream bos = new ByteArrayOutputStream();
KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
ks.load(null);
ks.setKeyEntry("key-alias", (Key) key, password.toCharArray(),
new java.security.cert.Certificate[]{x509Certificate});
ks.store(bos, password.toCharArray());
bos.close();
return bos.toByteArray();
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-06 12:29:06
Używam do tego pakietu klienta HTTP Apache commons w moim obecnym projekcie i działa dobrze z SSL i certyfikatem z własnym podpisem(po zainstalowaniu go w cacertach, jak wspomniałeś). Proszę spojrzeć na to tutaj:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-17 21:23:27
Myślę, że masz problem z certyfikatem serwera, nie jest to ważny certyfikat (myślę, że to właśnie oznacza" handshake_failure " w tym przypadku):
Zaimportuj certyfikat serwera do magazynu keystore trustcacerts w JRE klienta. Można to łatwo zrobić za pomocą keytool :
keytool
-import
-alias <provide_an_alias>
-file <certificate_file>
-keystore <your_path_to_jre>/lib/security/cacerts
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-18 08:55:31
Używając poniższego kodu
-Djavax.net.ssl.keyStoreType=pkcs12
Lub
System.setProperty("javax.net.ssl.keyStore", pathToKeyStore);
Nie jest wcale wymagane. Nie ma również potrzeby tworzenia własnej niestandardowej fabryki SSL.
Napotkałem również ten sam problem, w moim przypadku wystąpił problem, że kompletny łańcuch certyfikatów nie został zaimportowany do truststores. Import certyfikatów za pomocą keytool utility right FOM główny certyfikat, można również otworzyć plik cacerts w notatniku i sprawdzić, czy cały łańcuch certyfikatów jest importowany, czy nie. Sprawdź przy aliasie nazwa, którą podałeś podczas importowania certyfikatów, otwórz certyfikaty i zobacz, ile zawiera, taka sama liczba certyfikatów powinna znajdować się w pliku cacerts.
Również plik cacerts powinien być skonfigurowany na serwerze, na którym uruchomiona jest aplikacja, oba serwery będą się uwierzytelniać za pomocą kluczy publicznych/prywatnych.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-16 14:53:09