如何从密钥库中导出 .key 和 .crt 文件

18

在我搭建 Android 应用的开发环境时,需要为应用生成 SSL 证书。因此,我使用 keytool 为 Tomcat 生成了 keystore,并从中提取出证书,将其放入 .bks 文件以供 Android 使用,整个过程非常顺利。

现在,我们需要将所有服务器端代码迁移到需要 Apache HTTP 和 Tomcat 的服务器上。Apache HTTP SSL 需要 .key 和 .crt 文件,但是我找不到一种方法从 keystore 导出这些文件。

有人能提供帮助吗?我发现可以从 .pem 文件生成 .crt 文件。

openssl x509 -outform der -in your-cert.pem -out your-cert.crt

但是我该如何获取.key文件呢?

3个回答

22

Keytool(在JDK中可用)允许您将证书导出到文件:

keytool -exportcert -keystore [keystore] -alias [alias] -file [cert_file]

导出常规密钥应使用 -importkeystore 命令(惊喜):

keytool -importkeystore -srckeystore [keystore] -destkeystore [target-keystore] -deststoretype PKCS12

5
这种方法从来都不起作用,导出密钥不能这样做。 - Sohan
你介意解释一下为什么它对你不起作用吗? - hoaz
对于Apache来说,这不是导出的正确方式。首先需要以.p12格式导出密钥,然后只需导出证书以创建.crt文件,并仅导出密钥或使用OpenSSL创建.key文件。如果不这样做,会出现错误,证书不是有效的PEM文件。请参见: http://serverfault.com/questions/715827/how-to-generate-key-and-crt-file-from-jks-file-for-httpd-apache-server - Sohan
1
问题是如何导出密钥文件。将其转换为PEM格式已经在问题本身中解释过了。 - hoaz
1
密钥文件以 .p12 格式导出,但后续如何使用 OpenSSL 存储到 .key 文件中不太清楚。 - Sohan
https://security.stackexchange.com/a/66865/130215 这是一个更完整的答案。 - DustWolf

0
只需编写一个脚本来简化流程。
#!/usr/bin/env bash

# Extracts the private key and certificate from a Java keystore and saves them
#
# Ouputs:
#   <keystore>.p12: private key and certificate in PKCS12 format
#   <keystore>.pem: private key and certificate in PEM format
#   <keystore>.crt: certificate only
#   <keystore>.key: private key only

# Usage:
#   jks2pem.sh <keystore>

# Example:
#   jks2pem.sh keystore.jks

if [ -z "$1" ]; then
    echo "Usage: jks2pem.sh <keystore>.jks"
    exit 1
fi

base_name=$(basename "$1" .jks)
temp_password="changeit"

keytool -importkeystore -srckeystore "$1" -srcstoretype jks \
    -destkeystore "$base_name.p12" -deststoretype PKCS12 \
    -deststorepass "$temp_password"

# Export the private key and certificate as a PEM file without a password
openssl pkcs12 -nodes -in "$base_name.p12" -out "$base_name.pem" -passin pass:"$temp_password"

# Export the certificate as a PEM file
openssl pkcs12 -nokeys -in "$base_name.p12" -out "$base_name.crt" -passin pass:"$temp_password"

# Export the private key as a PEM file
openssl pkcs12 -nocerts -nodes -in "$base_name.p12" -out "$base_name.key" -passin pass:"$temp_password"

-4
您可以按照以下步骤创建新的密钥和自签名证书:
创建密钥和证书签名请求:
openssl req -newkey rsa:2048 -out cert.csr -keyout cert.key

创建pem:
openssl x509 -req -signkey cert.key -in cert.csr -out cert.pem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接