我在activemq config
中有这个<sslContext>
<sslContext keyStore="file:/home/alex/work/amq/broker.ks"
keyStorePassword="password" trustStore="file:${activemq.base}/conf/broker.ts"
trustStorePassword="password"/>
</sslContext>
我有一对x509证书和密钥文件
如何导入这两个用于ssl和ssl + stomp连接器?我可以谷歌的所有例子总是自己生成密钥,但我已经有了密钥。
我试过了
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.
我尝试连接证书和密钥但得到了相同的结果
如何导入密钥?
答案 0 :(得分:486)
我使用了以下两个步骤,我在其他答案中链接的评论/帖子中找到了这些步骤:
第一步:将x509 Cert和Key转换为pkcs12文件
openssl pkcs12 -export -in server.crt -inkey server.key \
-out server.p12 -name [some-alias] \
-CAfile ca.crt -caname root
注意:确保在p12文件上输入密码 - 否则在尝试导入时会出现空引用异常。 (如果其他人有这种头痛的话)。 (谢谢jocull!)
注2:您可能希望添加-chain
选项以保留完整的证书链。 (感谢Mafuba )
第二步:将pkcs12文件转换为java密钥库
keytool -importkeystore \
-deststorepass [changeit] -destkeypass [changeit] -destkeystore server.keystore \
-srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass some-password \
-alias [some-alias]
<强>完成强>
可选步骤零,创建自签名证书
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
干杯!
答案 1 :(得分:115)
Java 6中的Keytool确实具有此功能:Importing private keys into a Java keystore using keytool
以下是该帖子的基本细节。
使用OpenSSL将现有证书转换为PKCS12。当被问到或第二步会抱怨时需要密码。
openssl pkcs12 -export -in [my_certificate.crt] -inkey [my_key.key] -out [keystore.p12] -name [new_alias] -CAfile [my_ca_bundle.crt] -caname root
将PKCS12转换为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]
答案 2 :(得分:66)
不管你信不信,keytool不提供将私钥导入密钥库等基本功能。您可以通过将PKSC12文件与私钥合并到密钥库来尝试此workaround。
或者只是使用来自IBM的更加用户友好的KeyMan来进行密钥库处理而不是keytool.exe。
答案 3 :(得分:9)
还有一个:
#!/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"
答案 4 :(得分:8)
是的,keytool没有导入私钥的功能确实是一个可悲的事实。
为了记录,最后我使用了here
描述的解决方案答案 5 :(得分:7)
首先转换为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
答案 6 :(得分:6)
在我的情况下,我有一个pem文件,其中包含两个证书和一个用于相互SSL身份验证的加密私钥。 所以我的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
注意,如果私钥被加密,您需要提供密码(从原始pem文件的供应商处获取) 要转换成DER格式, 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);
答案 7 :(得分:5)
基于上面的答案,以下是如何使用keytool(需要JDK 1.6 +)从独立创建的Comodo证书和私钥创建基于Java的Web服务器的全新密钥库
发出此命令,并在密码提示符处输入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"
然后使用keytool将p12密钥库转换为jks密钥库:
keytool -importkeystore -deststorepass somepass -destkeypass somepass -destkeystore keystore.jks -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass somepass
然后导入从Comodo收到的其他两个根/中间证书:
导入COMODORSAAddTrustCA.crt:
keytool -import -trustcacerts -alias cert1 -file COMODORSAAddTrustCA.crt -keystore keystore.jks
导入COMODORSADomainValidationSecureServerCA.crt:
keytool -import -trustcacerts -alias cert2 -file COMODORSADomainValidationSecureServerCA.crt -keystore keystore.jks
答案 8 :(得分:4)
以下是将密钥导入现有密钥库时所遵循的步骤 - 来自此处和其他位置的答案的组合指令,以获取适用于我的Java密钥库的这些步骤:
openssl pkcs12 -export -in yourserver.crt -inkey yourkey.key -out server.p12 -name somename -certfile yourca.crt -caname root
(如果需要,请加上-chain选项。对我来说失败了)。 这将要求输入密码 - 您必须提供正确的密码,否则您将收到错误 (航向错误或填充错误等)。
*.jks
文件:keytool -importkeystore -srckeystore server.p12 -srcstoretype PKCS12 -destkeystore yourexistingjavakeystore.jks -deststoretype JKS -deststorepass existingjavastorepassword -destkeypass existingjavastorepassword
(非常重要 - 不要遗漏deststorepass和destkeypass参数。)
5.它会询问您src密钥库密码。输入Aragorn并按Enter键。
现在,证书和密钥已导入到现有的Java密钥库中。
答案 9 :(得分:3)
以前的答案正确指出,您只能通过首先将JKS文件转换为PKCS#12格式,使用标准JDK工具执行此操作。如果您感兴趣,我将一个紧凑的实用程序放在一起,将OpenSSL派生的密钥导入到JKS格式的密钥库中,而不必先将密钥库转换为PKCS#12:http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=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
答案 10 :(得分:2)
如果您有一个包含以下内容的PEM文件(例如server.pem
)
然后您可以将证书和密钥导入到JKS密钥库中,如下所示:
1 )将私钥从PEM文件复制到ascii文件(例如server.key
)
2 )将证书从PEM文件复制到ascii文件(例如server.crt
)
3 )将证书和密钥导出到PKCS12文件中:
$ openssl pkcs12 -export -in server.crt -inkey server.key \
-out server.p12 -name [some-alias] -CAfile server.pem -caname root
-CAfile
选项的参数。winpty
,以便可以输入导出密码。4 )将PKCS12文件转换为JKS密钥库:
$ keytool -importkeystore -deststorepass changeit -destkeypass changeit \
-destkeystore keystore.jks -srckeystore server.p12 -srcstoretype PKCS12 \
-srcstorepass changeit
srcstorepass
密码应与第3步中的导出密码匹配)答案 11 :(得分:2)
我想要达到的目的是使用已经提供的私钥和证书来对消息进行签名,该消息要去到某个地方,以确保消息是我发来的(私钥在公钥加密时签名)。
那么,如果您已经有一个.key文件和.crt文件?
尝试一下:
第一步:将密钥和证书转换为.p12文件
openssl pkcs12 -export -in certificate.crt -inkey privateKey.key -name alias -out yourconvertedfile.p12
步骤2:导入密钥并使用单个命令创建.jsk文件
keytool -importkeystore -deststorepass changeit -destkeystore keystore.jks -srckeystore umeme.p12 -srcstoretype PKCS12
步骤3:在您的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());
如果您需要使用此键签署一些字符串,请执行以下操作:
第1步:转换要加密的文本
byte[] data = "test".getBytes("UTF8");
第2步:获取base64编码的私钥
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));
参考文献:
最终程序
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));
}
答案 12 :(得分:0)
只需建立一个PKCS12密钥库,Java现在就可以直接使用它。实际上,如果您列出了Java风格的密钥库,keytool本身就会提醒您PKCS12现在是首选格式。
def count_reply(paket):
if len(reply)==0:
paket['count'] = 1
reply.append(paket)
found = True
else:
found = False
for itung in reply:
if itung['src']==paket['src'] and itung['dst']==paket['dst']:
itung['count']+=1
found = True
break
if not found:
reply.append(paket)
paket['count']=1
您应该已经从证书提供者处收到了所有三个文件(server.crt,server.key,ca.crt)。我不确定“ -caname root”的实际含义,但似乎必须这样指定。
在Java代码中,请确保指定正确的密钥库类型。
openssl pkcs12 -export -in server.crt -inkey server.key \
-out server.p12 -name [some-alias] \
-CAfile ca.crt -caname root -chain
这样,我的comodo.com颁发的SSL证书在NanoHTTPD中可以正常工作。
答案 13 :(得分:0)
在椭圆曲线的情况下,回答问题在Java密钥库中导入现有的x509证书和私钥,您可能还想看看这个线程How to read EC Private key in java which is in .pem file format >
答案 14 :(得分:0)
假设您已在/etc/letsencrypt/live/you.com
中使用Let's Encrypt创建了证书和私钥:
openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem -out pkcs.p12 \
-name letsencrypt
这会将您的SSL证书fullchain.pem
和私钥privkey.pem
合并到一个文件pkcs.p12
中。
系统会提示您输入pkcs.p12
的密码。
export
选项指定将创建PKCS#12文件,而不是对其进行解析(来自the manual)。
keytool -importkeystore -destkeystore keystore.jks -srckeystore pkcs.p12 \
-srcstoretype PKCS12 -alias letsencrypt
如果keystore.jks
不存在,将创建包含上面创建的pkcs.12
文件的文件。否则,您将pkcs.12
导入现有的密钥库中。
这些说明来自this blog post。
Here's more处理/etc/letsencrypt/live/you.com/
中不同类型的文件。
答案 15 :(得分:0)
如果您在单个 .pem 文件中收到了组合证书和密钥,例如 MongoDB Atlas 的身份验证,那么,
用文本编辑器打开pem
文件,将它们拆分成两个文件,例如cert.pem
和key.pem
(可以在文件中进行拆分的地方很清楚)和然后使用 openssl
命令创建一个 p12 格式的文件,如下所示:
openssl pkcs12 -export -out server.p12 -name test\
-in cert.pem -inkey key.pem
我使用的是 Java 8,结果证明至少在 Java 8 或更高版本中生成的 p12 (server.p12
) 现在是密钥库文件,因此您可以直接使用它而无需使用 {{1 }} 如果您不需要再添加任何证书。