Programing

SSL에서 사용하기 위해 Java 키 저장소에서 기존 X.509 인증서 및 개인 키를 가져 오는 방법은 무엇입니까?

lottogame 2020. 4. 27. 07:53
반응형

SSL에서 사용하기 위해 Java 키 저장소에서 기존 X.509 인증서 및 개인 키를 가져 오는 방법은 무엇입니까?


ActiveMQ 구성 에이 기능이 있습니다.

<sslContext>
        <sslContext keyStore="file:/home/alex/work/amq/broker.ks"  
 keyStorePassword="password" trustStore="file:${activemq.base}/conf/broker.ts" 
 trustStorePassword="password"/>
</sslContext>

X.509 인증서와 키 파일이 있습니다.

SSL 및 SSL + 스톰프 커넥터에서 사용하기 위해이 두 가지를 어떻게 가져 옵니까? Google이 항상 키 자체를 생성 할 수있는 모든 예제는 있지만 이미 키가 있습니다.

나는 시도했다

keytool -import  -keystore ./broker.ks -file mycert.crt

그러나 이것은 키 파일이 아닌 인증서 만 가져오고 결과는

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.

인증서와 키를 연결하려고 시도했지만 동일한 결과를 얻었습니다.

키를 어떻게 가져 옵니까?


keytool은 개인 키를 키 저장소로 가져 오기와 같은 기본 기능을 제공하지 않습니다. 개인 키가있는 PKSC12 파일을 키 저장소에 병합하여이 해결 방법시도 할 수 있습니다 .

또는 keytool.exe 대신 키 저장소를 처리하기 위해 IBM의 사용자 친화적 인 KeyMan 을 사용하십시오.


다른 답변에 링크 된 의견 / 게시물에서 찾은 다음 두 단계를 사용했습니다.

1 단계 : x.509 인증서 및 키를 pkcs12 파일로 변환

openssl pkcs12 -export -in server.crt -inkey server.key \
               -out server.p12 -name [some-alias] \
               -CAfile ca.crt -caname root

참고 : pkcs12 파일에 암호를 입력하십시오 . 그렇지 않으면 가져 오려고 할 때 널 포인터 예외가 발생합니다. (다른 사람 이이 두통을 앓은 경우). ( 감사합니다 jocull! )

참고 2 :-chain 전체 인증서 체인을 유지하는 옵션을 추가 할 수 있습니다 . ( 감사합니다 마 푸바 )

2 단계 : pkcs12 파일을 Java 키 저장소로 변환

keytool -importkeystore \
        -deststorepass [changeit] -destkeypass [changeit] -destkeystore server.keystore \
        -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass some-password \
        -alias [some-alias]

끝마친

선택 사항 0 단계 : 자체 서명 된 인증서 작성

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

건배!


Java 6의 Keytool에는 다음 기능이 있습니다. keytool을 사용하여 개인 키를 Java 키 저장소로 가져 오기

해당 게시물의 기본 세부 정보는 다음과 같습니다.

  1. OpenSSL을 사용하여 기존 인증서를 PKCS12로 변환하십시오. 요청시 비밀번호가 필요하거나 2 단계에서 불만이 표시됩니다.

    openssl pkcs12 -export -in [my_certificate.crt] -inkey [my_key.key] -out [keystore.p12] -name [new_alias] -CAfile [my_ca_bundle.crt] -caname root
    
  2. PKCS12를 Java Keystore 파일로 변환하십시오.

    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]
    

그리고 하나 더 :

#!/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"

예, keytool에는 개인 키를 가져 오는 기능이 없다는 것은 슬픈 일입니다.

기록을 위해 결국 여기에 설명 된 솔루션을 사용 했습니다.


먼저 p12로 변환하십시오.

openssl pkcs12 -export -in [filename-certificate] -inkey [filename-key] -name [host] -out [filename-new-PKCS-12.p12]

p12에서 새 JKS를 작성하십시오.

keytool -importkeystore -deststorepass [password] -destkeystore [filename-new-keystore.jks] -srckeystore [filename-new-PKCS-12.p12] -srcstoretype PKCS12

필자의 경우 상호 SSL 인증에 사용할 두 개의 인증서와 암호화 된 개인 키가 포함 된 pem 파일이있었습니다. 그래서 내 pem 파일은 다음과 같습니다.

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

여기 내가 한 일이 있습니다.

"--- BEGIN .."으로 시작하고 "--- END .."행으로 끝나는 각 항목에 하나의 항목 만 포함되도록 파일을 세 개의 개별 파일로 분할하십시오. cert1.pem cert2.pem 및 pkey.pem이라는 세 개의 파일이 있다고 가정합니다.

openssl과 다음 구문을 사용하여 pkey.pem을 DER 형식으로 변환하십시오.

openssl pkcs8 -topk8 -nocrypt -in pkey.pem -inform PEM -out pkey.der -outform DER

개인 키가 암호화 된 경우 DER 형식으로 변환하려면 암호를 제공해야합니다 (원래 pem 파일의 공급자로부터 입수). openssl은 다음과 같이 암호를 묻습니다. "pkey에 암호를 입력하십시오. .pem : "변환이 성공하면"pkey.der "라는 새 파일이 나타납니다.

새 Java 키 저장소를 작성하고 개인 키 및 인증서를 가져 오십시오.

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());

(선택 사항) 새 키 저장소의 컨텐츠를 확인하십시오.

keytool -list -keystore mykeystore -storepass password

키 저장소 유형 : JKS 키 저장소 제공자 : SUN

키 저장소에 3 개의 항목이 있습니다.

cn = ..., ou = ..., o = .., 2014 년 9 월 2 일, trustedCertEntry, 인증서 지문 (SHA1) : 2C : B8 : ...

importkey, 2014 년 9 월 2 일, PrivateKeyEntry, 인증서 지문 (SHA1) : 9C : B0 : ...

cn = ..., o = ...., 2014 년 9 월 2 일, trustedCertEntry, 인증서 지문 (SHA1) : 83:63 : ...

(선택 사항) SSL 서버에 대해 새 키 저장소의 인증서 및 개인 키를 테스트하십시오 (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..

인증서를 사용할 계획이라면 HttpsURLConnection에 인증서를 등록하십시오.

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

위의 답변을 기반으로, 독립적으로 작성된 Comodo 인증서 및 keytool을 사용하여 개인 키에서 Java 기반 웹 서버에 대한 새로운 키 저장소를 작성하는 방법은 다음과 같습니다 (JDK 1.6 이상 필요).

  1. 이 명령을 실행하고 비밀번호 프롬프트에 somepass를 입력하십시오. 'server.crt'는 서버의 인증서이고 'server.key'는 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"

  2. 그런 다음 keytool을 사용하여 p12 키 저장소를 jks 키 저장소로 변환하십시오. keytool -importkeystore -deststorepass somepass -destkeypass somepass -destkeystore keystore.jks -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass somepass

그런 다음 Comodo로부터받은 다른 두 루트 / 중간 인증서를 가져옵니다.

  1. COMODORSAAddTrustCA.crt 가져 오기 : keytool -import -trustcacerts -alias cert1 -file COMODORSAAddTrustCA.crt -keystore keystore.jks

  2. COMODORSADomainValidationSecureServerCA.crt 가져 오기 : keytool -import -trustcacerts -alias cert2 -file COMODORSADomainValidationSecureServerCA.crt -keystore keystore.jks


이 단계를 사용하여 키를 기존 키 저장소로 가져올 수 있습니다. 이 글과 다른 사이트의 답변에서 지침을 결합합니다. 이 지침은 저에게 효과적이었습니다 (Java 키 저장소).

  1. 운영

openssl pkcs12 -export -in yourserver.crt -inkey yourkey.key -out server.p12 -name somename -certfile yourca.crt -caname root

(필요한 경우 -chain 옵션을 넣으십시오. 퍼팅에 실패했습니다). 암호를 묻는 메시지가 표시됩니다. 정확한 암호를 입력해야합니다. 그렇지 않으면 오류 (제목 오류 또는 패딩 오류 등)가 표시됩니다.

  1. 새 비밀번호를 입력하라는 메시지가 표시됩니다. 여기에 비밀번호를 입력해야합니다. 아무것도 입력하고 기억하십시오. (아라곤으로 들어간 것으로 가정하자).
  2. 이것은 pkcs 형식으로 server.p12 파일을 작성합니다.
  3. 이제 *.jks파일 실행 으로 가져 오려면 다음을 수행하십시오.
    keytool -importkeystore -srckeystore server.p12 -srcstoretype PKCS12 -destkeystore yourexistingjavakeystore.jks -deststoretype JKS -deststorepass existingjavastorepassword -destkeypass existingjavastorepassword
    (매우 중요-deststorepass 및 destkeypass 매개 변수를 생략하지 마십시오.)
  4. src 키 저장소 비밀번호를 묻습니다. 아라곤을 입력하고 엔터를 누르십시오. 이제 인증서 및 키를 기존 Java 키 저장소로 가져옵니다.

이전 답변은 JKS 파일을 PKCS # 12 형식으로 먼저 변환하여 표준 JDK 도구로만 수행 할 수 있음을 올바르게 지적합니다. 관심이 있으시면 먼저 키 저장소를 PKCS # 12로 변환하지 않고도 OpenSSL 파생 키를 JKS 형식의 키 저장소로 가져 오는 간단한 유틸리티를 준비했습니다 ( http://commandlinefanatic.com/cgi-bin/showarticle). cgi? 기사 = art049

다음과 같이 링크 된 유틸리티를 사용하십시오.

$ openssl req -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.csr -subj "/CN=localhost"

(CSR에 서명하고 localhost.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

다음을 포함하는 PEM 파일 (예 :)이있는 경우 server.pem:

  • 신뢰할 수있는 인증서
  • 개인 키

그런 다음 인증서와 키를 다음과 같이 JKS 키 저장소로 가져올 수 있습니다.

1 ) 예 (ASCII 파일로 PEM 파일에서 개인 키를 복사 server.key)

2 ) (ASCII 파일로 예를 PEM 파일에서 인증서를 복사 server.crt)

3 ) 인증서와 키를 PKCS12 파일로 내 보냅니다.

$ openssl pkcs12 -export -in server.crt -inkey server.key \
                 -out server.p12 -name [some-alias] -CAfile server.pem -caname root
  • PEM 파일을 -CAfile옵션 의 인수로 사용할 수 있습니다 .
  • '내보내기'비밀번호를 묻는 메시지가 표시됩니다.
  • git bash 에서이 작업을 수행하는 경우 winpty내보내기 암호를 입력 할 수 있도록 명령 시작에 추가하십시오 .

4 ) PKCS12 파일을 JKS 키 저장소로 변환하십시오.

$ keytool -importkeystore -deststorepass changeit -destkeypass changeit \
          -destkeystore keystore.jks  -srckeystore server.p12 -srcstoretype PKCS12 \
          -srcstorepass changeit
  • srcstorepass암호) 3 단계에서 수출 암호와 일치해야한다

내가 달성하려고했던 것은 이미 제공된 개인 키와 인증서를 사용하여 메시지가 나에게서 온 것인지 확인하는 데 필요한 메시지에 서명하는 것입니다 (공개 키는 암호화하는 동안 개인 키 서명).

.key 파일과 .crt 파일이 이미 있다면?

Try this:

Step1: Convert the key and cert to .p12 file

openssl pkcs12 -export -in certificate.crt -inkey privateKey.key -name alias -out yourconvertedfile.p12

Step 2: Import the key and create a .jsk file with a single command

keytool -importkeystore -deststorepass changeit -destkeystore keystore.jks -srckeystore umeme.p12 -srcstoretype PKCS12

Step 3: In your java:

char[] keyPassword = "changeit".toCharArray();

KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream keyStoreData = new FileInputStream("keystore.jks");

keyStore.load(keyStoreData, keyPassword);
KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(keyPassword);
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry("alias", entryPassword);

System.out.println(privateKeyEntry.toString());

If you need to sign some string using this key do the following:

Step 1: Convert the text you want to encrypt

byte[] data = "test".getBytes("UTF8");

Step 2: Get base64 encoded private key

keyStore.load(keyStoreData, keyPassword);

//get cert, pubkey and private key from the store by alias
Certificate cert = keyStore.getCertificate("localhost");
PublicKey publicKey = cert.getPublicKey();
KeyPair keyPair = new KeyPair(publicKey, (PrivateKey) key);

//sign with this alg
Signature sig = Signature.getInstance("SHA1WithRSA");
sig.initSign(keyPair.getPrivate());
sig.update(data);
byte[] signatureBytes = sig.sign();
System.out.println("Signature:" + Base64.getEncoder().encodeToString(signatureBytes));

sig.initVerify(keyPair.getPublic());
sig.update(data);

System.out.println(sig.verify(signatureBytes));

References:

  1. How to import an existing x509 certificate and private key in Java keystore to use in SSL?
  2. http://tutorials.jenkov.com/java-cryptography/keystore.html
  3. http://www.java2s.com/Code/Java/Security/RetrievingaKeyPairfromaKeyStore.htm
  4. How to sign string with private key

Final program

public static void main(String[] args) throws Exception {

    byte[] data = "test".getBytes("UTF8");

    // load keystore
    char[] keyPassword = "changeit".toCharArray();

    KeyStore keyStore = KeyStore.getInstance("JKS");
    //System.getProperty("user.dir") + "" < for a file in particular path 
    InputStream keyStoreData = new FileInputStream("keystore.jks");
    keyStore.load(keyStoreData, keyPassword);

    Key key = keyStore.getKey("localhost", keyPassword);

    Certificate cert = keyStore.getCertificate("localhost");

    PublicKey publicKey = cert.getPublicKey();

    KeyPair keyPair = new KeyPair(publicKey, (PrivateKey) key);

    Signature sig = Signature.getInstance("SHA1WithRSA");

    sig.initSign(keyPair.getPrivate());
    sig.update(data);
    byte[] signatureBytes = sig.sign();
    System.out.println("Signature:" + Base64.getEncoder().encodeToString(signatureBytes));

    sig.initVerify(keyPair.getPublic());
    sig.update(data);

    System.out.println(sig.verify(signatureBytes));
}

Using Let's Encrypt certificates

Assuming you've created your certificates and private keys with Let's Encrypt in /etc/letsencrypt/live/you.com:

1. Create a PKCS #12 file

openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem -out pkcs.p12 \
        -name letsencrypt

This combines your SSL certificate fullchain.pem and your private key privkey.pem into a single file, pkcs.p12.

You'll be prompted for a password for pkcs.p12.

The export option specifies that a PKCS #12 file will be created rather than parsed (from the manual).

2. Create the Java keystore

keytool -importkeystore -destkeystore keystore.jks -srckeystore pkcs.p12 \
        -srcstoretype PKCS12 -alias letsencrypt

If keystore.jks doesn't exist, it will be created containing the pkcs.12 file created above. Otherwise, you'll import pkcs.12 into the existing keystore.


These instructions are derived from this blog post.

Here's more on the different kind of files in /etc/letsencrypt/live/you.com/.


Just make a PKCS12 keystore, Java can use it directly now. In fact, if you list a Java-style keystore, keytool itself alerts you to the fact that PKCS12 is now the preferred format.

openssl pkcs12 -export -in server.crt -inkey server.key \
               -out server.p12 -name [some-alias] \
               -CAfile ca.crt -caname root -chain

You should have received all three files (server.crt, server.key, ca.crt) from your certificate provider. I am not sure what "-caname root" actually means, but it seems to have to be specified that way.

In the Java code, make sure to specify the right keystore type.

KeyStore.getInstance("PKCS12")

I got my comodo.com-issued SSL certificate working fine in NanoHTTPD this way.


in a case of Elliptic Curve and answer the question import an existing x509 certificate and private key in Java keystore, you may want to have a look also to this thread How to read EC Private key in java which is in .pem file format

참고URL : https://stackoverflow.com/questions/906402/how-to-import-an-existing-x-509-certificate-and-private-key-in-java-keystore-to

반응형