openssl生成自签名证书

1.安装openssl

yum install -y openssl openssl-devel

2.清空内容

rm /etc/pki/CA/index.txt
touch /etc/pki/CA/index.txt
echo 01 | sudo tee /etc/pki/CA/serial

3.生成CA证书和私钥

# 创建CA私钥
openssl genrsa -out ca.key 2048
# 创建CA证书
openssl req -new -x509 -days 3650 -key ca.key -out ca.crt -subj "/C=CN/ST=GuangDong/L=ShenZhen/O=BaiQiShi/OU=CA Test"

4.生成服务器证书签署请求和私钥

# 创建服务器私钥
openssl genrsa -out server.key 2048
# 创建服务器证书签署请求CSR,Server/CN=后面接域名或IP地址
openssl req -new -days 365 -key server.key -out server.csr -subj "/C=CN/ST=GuangDong/L=ShenZhen/O=BaiQiShi/OU=Gateway Server/CN=192.168.1.150"

5.使用自己的CA进行签署证书

# 执行命令后输入2次Y
openssl ca -in server.csr -out server.crt -cert ca.crt  -keyfile ca.key

6.合并证书

server.crt文件是包含两部分内容,一是Certificate描述内容,二是CERTIFICATE签名内容。

操作步骤:
①删除server.crt的第一部分Certificate描述内容
②复制ca.crt内容复制到server.crt

7.转换为pkcs12格式

openssl pkcs12 -export -clcerts -in server.crt -inkey server.key -out server.p12

输入密码,并记住密码

8.转换为jks格式

keytool -importkeystore -srckeystore server.p12 -destkeystore server.jks -srcstoretype pkcs12 -deststoretype jks

输入密码

9.查看证书

keytool -list -v -keystore server.jks

问题排查

1.提示/etc/pki/CA/index.txt: No such file or directory

Using configuration from /etc/pki/tls/openssl.cnf
/etc/pki/CA/index.txt: No such file or directory
unable to open '/etc/pki/CA/index.txt'
140306692044688:error:02001002:system library:fopen:No such file or directory:bss_file.c:402:fopen('/etc/pki/CA/index.txt','r')
140306692044688:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:404:

解决办法:

touch /etc/pki/CA/index.txt

2.提示/etc/pki/CA/serial: No such file or directory

Using configuration from /etc/pki/tls/openssl.cnf
/etc/pki/CA/serial: No such file or directory
error while loading serial number
140643143149456:error:02001002:system library:fopen:No such file or directory:bss_file.c:402:fopen('/etc/pki/CA/serial','r')
140643143149456:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:404:

解决办法:

echo 01 | sudo tee /etc/pki/CA/serial

3.提示wrong number of fields on line 1 (looking for field 6, got 1, '' left)

Using configuration from /etc/pki/tls/openssl.cnf
wrong number of fields on line 1 (looking for field 6, got 1, '' left)

解决办法:

清空index.txt内容,注意是0字节

rm /etc/pki/CA/index.txt
touch /etc/pki/CA/index.txt

参考:

使用openssl生成包含证书链的java用jks证书

如果觉得我的文章对你有用,请随意赞赏