我们可以使用openssl生成一对密钥和证书。通常,证书文件(.crt)包含公钥和证书信息,而.key文件是私钥。
我们可以使用以下步骤:
-
生成私钥(.key文件)
-
使用私钥生成证书签名请求(CSR)
-
使用私钥和CSR生成自签名证书(.crt文件)
注意:这里生成的是自签名证书,适用于测试或内部使用。对于生产环境,通常需要向证书颁发机构(CA)申请签名。
方法一:生成自签名证书(一步完成)
bash
# 生成私钥和自签名证书(有效期365天)
openssl req -x509 -newkey rsa:2048 -keyout server.key -out server.crt -days 365 -nodes
# 交互式输入信息,或使用以下命令自动填写:
openssl req -x509 -newkey rsa:2048 -keyout server.key -out server.crt -days 365 -nodes \
-subj "/C=CN/ST=Beijing/L=Beijing/O=YourOrg/OU=YourDept/CN=yourdomain.com"
方法二:分步生成(更灵活)
bash
# 1. 生成私钥
openssl genrsa -out server.key 2048
# 2. 生成证书签名请求(CSR)
openssl req -new -key server.key -out server.csr \
-subj "/C=CN/ST=Beijing/L=Beijing/O=YourOrg/OU=YourDept/CN=yourdomain.com"
# 3. 生成自签名证书
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
方法三:使用配置文件生成
- 创建配置文件
cert.conf:
bash
[req]
default_bits = 2048
prompt = no
default_md = sha256
distinguished_name = dn
x509_extensions = v3_req
[dn]
C = CN
ST = Beijing
L = Beijing
O = YourOrg
OU = YourDept
CN = yourdomain.com
[v3_req]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = yourdomain.com
DNS.2 = *.yourdomain.com
IP.1 = 192.168.1.100
- 执行生成命令:
bash
openssl req -new -x509 -days 365 -nodes \
-config cert.conf \
-newkey rsa:2048 \
-keyout server.key \
-out server.crt
常用参数说明:
-
-newkey rsa:2048:生成 2048 位 RSA 密钥 -
-keyout:指定私钥输出文件 -
-out:指定证书输出文件 -
-days:证书有效期(天) -
-nodes:不加密私钥(无密码) -
-subj:自动填写证书信息 -
-x509:生成自签名证书
验证生成的证书:
bash
# 查看证书信息
openssl x509 -in server.crt -text -noout
# 查看私钥信息
openssl rsa -in server.key -check -noout
# 验证密钥和证书是否匹配
openssl x509 -noout -modulus -in server.crt | openssl md5
openssl rsa -noout -modulus -in server.key | openssl md5
# 两个MD5值应该相同
安全提示:
-
保护私钥:私钥文件 (.key) 应严格保密
-
密码保护 (可选):移除
-nodes参数可设置私钥密码 -
生产环境:自签名证书仅用于测试,生产环境应使用 CA 颁发的证书
-
密钥长度:推荐使用 2048 位或以上