Jak zaimportować istniejący certyfikat x509 i klucz prywatny W Java keystore do użycia W SSL?
Mam to w config activemq
<sslContext>
<sslContext keyStore="file:/home/alex/work/amq/broker.ks"
keyStorePassword="password" trustStore="file:${activemq.base}/conf/broker.ts"
trustStorePassword="password"/>
</sslContext>
Mam parę x509 cert i plik klucza
Jak zaimportować te dwa do użycia w złączach ssl I ssl+stomp? Wszystkie przykłady mogę google zawsze generować klucz samodzielnie, ale mam już klucz.
Próbowałem
keytool -import -keystore ./broker.ks -file mycert.crt
Ale to tylko importuje certyfikat, a nie Plik klucza i skutkuje
2009-05-25 13:16:24,270 [localhost:61612] ERROR TransportConnector - Could not accept connection : No available certificate or key corresponds to the SSL cipher suites which are enabled.
Próbowałem połączyć cert i klucz, ale dostałem to samo wynik
Jak zaimportować klucz?
10 answers
Wierzcie lub nie, keytool nie zapewnia takich podstawowych funkcji, jak importowanie klucza prywatnego do keystore. Możesz spróbować obejścia tego problemu przy połączeniu pliku PKSC12 z kluczem prywatnym do magazynu kluczy.
Zamiast keytool, możesz użyć bardziej przyjaznego dla użytkownika Keymana z IBM.exe.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
2012-10-24 10:58:55
Użyłem następujących dwóch kroków, które znalazłem w komentarzach/postach powiązanych z innymi odpowiedziami:
Krok pierwszy: przekonwertuj X509 Cert i klucz do pliku pkcs12
openssl pkcs12 -export -in server.crt -inkey server.key \
-out server.p12 -name [some-alias] \
-CAfile ca.crt -caname root
Uwaga: upewnij się, że umieściłeś hasło w pliku p12 - w przeciwnym razie otrzymasz wyjątek null reference podczas próby zaimportowania go. (Na wypadek, gdyby ktoś jeszcze miał ten ból głowy). (dzięki jocull!)
Uwaga 2: możesz dodać opcję -chain
, Aby zachować pełną łańcuch certyfikatów. ( Dzięki Mafuba )
Krok drugi: przekonwertuj plik pkcs12 na klucz java
keytool -importkeystore \
-deststorepass [changeit] -destkeypass [changeit] -destkeystore server.keystore \
-srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass some-password \
-alias [some-alias]
Zakończone
Opcjonalny krok Zero, Utwórz certyfikat z własnym podpisem
openssl genrsa -out server.key 2048
openssl req -new -out server.csr -key server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Zdrówko!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
2015-06-17 14:04:51
Keytool w Javie 6 ma taką możliwość: Importowanie kluczy prywatnych do magazynu kluczy Javy za pomocą keytool
Oto podstawowe szczegóły z tego postu.
-
Konwersja istniejącego cert na PKCS12 przy użyciu OpenSSL. Hasło jest wymagane, gdy zostanie zapytane lub 2. krok będzie narzekać.
openssl pkcs12 -export -in [my_certificate.crt] -inkey [my_key.key] -out [keystore.p12] -name [new_alias] -CAfile [my_ca_bundle.crt] -caname root
-
Konwersja PKCS12 do pliku Keystore Java.
keytool -importkeystore -deststorepass [new_keystore_pass] -destkeypass [new_key_pass] -destkeystore [keystore.jks] -srckeystore [keystore.p12] -srcstoretype PKCS12 -srcstorepass [pass_used_in_p12_keystore] -alias [alias_used_in_p12_keystore]
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
2018-03-06 09:55:08
I jeszcze jedno:
#!/bin/bash
# We have:
#
# 1) $KEY : Secret key in PEM format ("-----BEGIN RSA PRIVATE KEY-----")
# 2) $LEAFCERT : Certificate for secret key obtained from some
# certification outfit, also in PEM format ("-----BEGIN CERTIFICATE-----")
# 3) $CHAINCERT : Intermediate certificate linking $LEAFCERT to a trusted
# Self-Signed Root CA Certificate
#
# We want to create a fresh Java "keystore" $TARGET_KEYSTORE with the
# password $TARGET_STOREPW, to be used by Tomcat for HTTPS Connector.
#
# The keystore must contain: $KEY, $LEAFCERT, $CHAINCERT
# The Self-Signed Root CA Certificate is obtained by Tomcat from the
# JDK's truststore in /etc/pki/java/cacerts
# The non-APR HTTPS connector (APR uses OpenSSL-like configuration, much
# easier than this) in server.xml looks like this
# (See: https://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html):
#
# <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
# SSLEnabled="true"
# maxThreads="150" scheme="https" secure="true"
# clientAuth="false" sslProtocol="TLS"
# keystoreFile="/etc/tomcat6/etl-web.keystore.jks"
# keystorePass="changeit" />
#
# Let's roll:
TARGET_KEYSTORE=/etc/tomcat6/foo-server.keystore.jks
TARGET_STOREPW=changeit
TLS=/etc/pki/tls
KEY=$TLS/private/httpd/foo-server.example.com.key
LEAFCERT=$TLS/certs/httpd/foo-server.example.com.pem
CHAINCERT=$TLS/certs/httpd/chain.cert.pem
# ----
# Create PKCS#12 file to import using keytool later
# ----
# From https://www.sslshopper.com/ssl-converter.html:
# The PKCS#12 or PFX format is a binary format for storing the server certificate,
# any intermediate certificates, and the private key in one encryptable file. PFX
# files usually have extensions such as .pfx and .p12. PFX files are typically used
# on Windows machines to import and export certificates and private keys.
TMPPW=$$ # Some random password
PKCS12FILE=`mktemp`
if [[ $? != 0 ]]; then
echo "Creation of temporary PKCS12 file failed -- exiting" >&2; exit 1
fi
TRANSITFILE=`mktemp`
if [[ $? != 0 ]]; then
echo "Creation of temporary transit file failed -- exiting" >&2; exit 1
fi
cat "$KEY" "$LEAFCERT" > "$TRANSITFILE"
openssl pkcs12 -export -passout "pass:$TMPPW" -in "$TRANSITFILE" -name etl-web > "$PKCS12FILE"
/bin/rm "$TRANSITFILE"
# Print out result for fun! Bug in doc (I think): "-pass " arg does not work, need "-passin"
openssl pkcs12 -passin "pass:$TMPPW" -passout "pass:$TMPPW" -in "$PKCS12FILE" -info
# ----
# Import contents of PKCS12FILE into a Java keystore. WTF, Sun, what were you thinking?
# ----
if [[ -f "$TARGET_KEYSTORE" ]]; then
/bin/rm "$TARGET_KEYSTORE"
fi
keytool -importkeystore \
-deststorepass "$TARGET_STOREPW" \
-destkeypass "$TARGET_STOREPW" \
-destkeystore "$TARGET_KEYSTORE" \
-srckeystore "$PKCS12FILE" \
-srcstoretype PKCS12 \
-srcstorepass "$TMPPW" \
-alias foo-the-server
/bin/rm "$PKCS12FILE"
# ----
# Import the chain certificate. This works empirically, it is not at all clear from the doc whether this is correct
# ----
echo "Importing chain"
TT=-trustcacerts
keytool -import $TT -storepass "$TARGET_STOREPW" -file "$CHAINCERT" -keystore "$TARGET_KEYSTORE" -alias chain
# ----
# Print contents
# ----
echo "Listing result"
keytool -list -storepass "$TARGET_STOREPW" -keystore "$TARGET_KEYSTORE"
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
2015-07-27 23:08:26
Tak, to rzeczywiście smutny fakt, że keytool nie ma funkcji importowania klucza prywatnego.
Dla przypomnienia, na koniec wybrałem rozwiązanie opisane 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
2016-09-10 03:26:17
W moim przypadku miałem plik pem, który zawierał dwa certyfikaty i zaszyfrowany klucz prywatny do wykorzystania w wzajemnym uwierzytelnianiu SSL. Więc mój plik pem wyglądał tak:
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,C8BF220FC76AA5F9
...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
Oto co zrobiłem:
Podziel plik na trzy oddzielne pliki, tak aby każdy z nich zawierał tylko jeden wpis, zaczynając od " - - - BEGIN.."i kończy się na" - - - koniec.."wiersze. Załóżmy, że mamy teraz trzy pliki: cert1.pem cert2.pem i pkey.pem
Konwertuj pkey.pem do formatu DER przy użyciu openssl i następująca składnia:
openssl pkcs8 -topk8 -nocrypt -in pkey.pem -inform PEM -out pkey.der -outform DER
Zauważ, że jeśli klucz prywatny jest zaszyfrowany, musisz podać hasło (uzyskać je od dostawcy oryginalnego pliku pem ) aby przekonwertować do formatu DER, openssl poprosi Cię o hasło w następujący sposób: "wprowadź hasło dla pkey.pem: " Jeśli konwersja się powiedzie, otrzymasz nowy plik o nazwie "pkey.der "
Utwórz nowy magazyn kluczy java i zaimportuj klucz prywatny i certyfikaty:
String keypass = "password"; // this is a new password, you need to come up with to protect your java key store file
String defaultalias = "importkey";
KeyStore ks = KeyStore.getInstance("JKS", "SUN");
// this section does not make much sense to me,
// but I will leave it intact as this is how it was in the original example I found on internet:
ks.load( null, keypass.toCharArray());
ks.store( new FileOutputStream ( "mykeystore" ), keypass.toCharArray());
ks.load( new FileInputStream ( "mykeystore" ), keypass.toCharArray());
// end of section..
// read the key file from disk and create a PrivateKey
FileInputStream fis = new FileInputStream("pkey.der");
DataInputStream dis = new DataInputStream(fis);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
byte[] key = new byte[bais.available()];
KeyFactory kf = KeyFactory.getInstance("RSA");
bais.read(key, 0, bais.available());
bais.close();
PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec ( key );
PrivateKey ff = kf.generatePrivate (keysp);
// read the certificates from the files and load them into the key store:
Collection col_crt1 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert1.pem"));
Collection col_crt2 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert2.pem"));
Certificate crt1 = (Certificate) col_crt1.iterator().next();
Certificate crt2 = (Certificate) col_crt2.iterator().next();
Certificate[] chain = new Certificate[] { crt1, crt2 };
String alias1 = ((X509Certificate) crt1).getSubjectX500Principal().getName();
String alias2 = ((X509Certificate) crt2).getSubjectX500Principal().getName();
ks.setCertificateEntry(alias1, crt1);
ks.setCertificateEntry(alias2, crt2);
// store the private key
ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), chain );
// save the key store to a file
ks.store(new FileOutputStream ( "mykeystore" ),keypass.toCharArray());
(opcjonalnie) zweryfikuj zawartość z twojego nowego sklepu z kluczami:
keytool -list -keystore mykeystore -storepass password
Keystore type: JKS keystore provider: SUN
Twój keystore zawiera 3 wpisy
Cn=..., ou=...,o=.., 2 września 2014, trustedCertEntry, certyfikat odcisk palca (SHA1): 2C:B8: ...
Importkey, 2 września 2014, PrivateKeyEntry, odcisk palca certyfikatu (SHA1): 9C: B0: ...
Cn=...,o=...., 2 września 2014, trustedCertEntry, Certificate fingerprint (SHA1): 83: 63: ...
(opcjonalnie) Przetestuj swoje certyfikaty i klucz prywatny z nowego magazynu kluczy pod kątem serwera SSL: ( Możesz chcieć włączyć debugowanie jako opcję VM: - Djavax. net. debug=all)
char[] passw = "password".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS", "SUN");
ks.load(new FileInputStream ( "mykeystore" ), passw );
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passw);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager[] tm = tmf.getTrustManagers();
SSLContext sclx = SSLContext.getInstance("TLS");
sclx.init( kmf.getKeyManagers(), tm, null);
SSLSocketFactory factory = sclx.getSocketFactory();
SSLSocket socket = (SSLSocket) factory.createSocket( "192.168.1.111", 443 );
socket.startHandshake();
//if no exceptions are thrown in the startHandshake method, then everything is fine..
Wreszcie zarejestruj swoje certyfikaty za pomocą HttpsURLConnection, jeśli planujesz go użyć:
char[] passw = "password".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS", "SUN");
ks.load(new FileInputStream ( "mykeystore" ), passw );
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passw);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager[] tm = tmf.getTrustManagers();
SSLContext sclx = SSLContext.getInstance("TLS");
sclx.init( kmf.getKeyManagers(), tm, null);
HostnameVerifier hv = new HostnameVerifier()
{
public boolean verify(String urlHostName, SSLSession session)
{
if (!urlHostName.equalsIgnoreCase(session.getPeerHost()))
{
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultSSLSocketFactory( sclx.getSocketFactory() );
HttpsURLConnection.setDefaultHostnameVerifier(hv);
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
2016-05-18 13:17:26
Pierwsza konwersja na p12:
openssl pkcs12 -export -in [filename-certificate] -inkey [filename-key] -name [host] -out [filename-new-PKCS-12.p12]
Utwórz nowy JKS z p12:
keytool -importkeystore -deststorepass [password] -destkeystore [filename-new-keystore.jks] -srckeystore [filename-new-PKCS-12.p12] -srcstoretype PKCS12
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
2017-06-01 08:49:59
Na podstawie powyższych odpowiedzi, oto jak utworzyć nowy keystore dla serwera www opartego na Javie, z niezależnie stworzonego certyfikatu Comodo i klucza prywatnego przy użyciu keytool (wymaga JDK 1.6+)
Wykonaj to polecenie i w wierszu hasła wprowadź somepass - ' server.crt 'to cert twojego serwera i' server.key " jest kluczem prywatnym, którego użyłeś do wydania CSR:
openssl pkcs12 -export -in server.crt -inkey server.key -out server.p12 -name www.yourdomain.com -CAfile AddTrustExternalCARoot.crt -caname "AddTrust External CA Root"
Następnie użyj keytool, aby przekształcić keystore P12 w jks keystore:
keytool -importkeystore -deststorepass somepass -destkeypass somepass -destkeystore keystore.jks -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass somepass
Następnie zaimportuj dwa pozostałe certy root/intermediate, które otrzymałeś od Comodo:
Import COMODORSAAddTrustCA.crt:
keytool -import -trustcacerts -alias cert1 -file COMODORSAAddTrustCA.crt -keystore keystore.jks
Import COMODORSADomainValidationSecureServerca.crt:
keytool -import -trustcacerts -alias cert2 -file COMODORSADomainValidationSecureServerCA.crt -keystore keystore.jks
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
2017-12-21 17:32:13
Oto kroki, które wykonałem, aby zaimportować klucz do istniejącego klucza-połączone instrukcje z odpowiedzi tutaj i innych miejsc, aby uzyskać te kroki, które działały dla mojego klucza java:
- Run
openssl pkcs12 -export -in yourserver.crt -inkey yourkey.key -out server.p12 -name somename -certfile yourca.crt -caname root
(w razie potrzeby umieść opcję-chain. Putting that failed for me). To poprosi o hasło - musisz podać poprawne hasło, w przeciwnym razie pojawi się błąd (błąd nagłówka lub błąd wypełnienia itp.).
- poprosi Cię o wprowadzenie nowego hasło-tutaj musisz wpisać hasło-Wpisz cokolwiek, ale zapamiętaj. (Załóżmy, że wejdziesz do Aragorna).
- spowoduje utworzenie serwera.plik p12 w formacie pkcs.
- Teraz Aby zaimportować go do pliku
*.jks
Uruchom:
Keytool-importkeystore-serwer srckeystore.p12-srcstoretype PKCS12 - destkeystore musisz zrobić to samo.jks-deststoretype JKS-deststorepass existingjavastorepassword-destkeypass existingjavastorepassword
(bardzo ważne - nie pomiń deststorepass i parametry destkeypass.)
5. Poprosi Cię o hasło do przechowywania kluczy src. Wpisz Aragorn i naciśnij enter.
Certyfikat i klucz są teraz importowane do istniejącego magazynu kluczy java.
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
2017-07-13 14:27:25
Poprzednie odpowiedzi wskazują poprawnie, że można to zrobić tylko za pomocą standardowych narzędzi JDK, konwertując najpierw plik JKS do formatu PKCS #12. Jeśli jesteś zainteresowany, przygotowałem kompaktowe narzędzie do importowania kluczy pochodnych OpenSSL do sformatowanego JKS-a, bez konieczności konwertowania klucza do PKCS #12: http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art049
Użyłbyś linked utility w ten sposób:
$ openssl req -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.csr -subj "/CN=localhost"
(podpisz CSR, Pobierz tylny host lokalny.cer)
$ openssl rsa -in localhost.key -out localhost.rsa
Enter pass phrase for localhost.key:
writing RSA key
$ java -classpath . KeyImport -keyFile localhost.rsa -alias localhost -certificateFile localhost.cer -keystore localhost.jks -keystorePassword changeit -keystoreType JKS -keyPassword changeit
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
2016-03-03 18:47:22