Linux

关注公众号 jb51net

关闭
首页 > 网站技巧 > 服务器 > Linux > 通过OpenSSL生成自签名证书

如何通过OpenSSL生成自签名证书

作者:ICT董老师

文章介绍了如何使用OpenSSL生成一对密钥和证书,包括生成私钥、证书签名请求(CSR)和自签名证书的过程,还提供了分步生成证书的方法,并说明了配置文件的创建和使用,文章还强调了私钥的安全性,并建议在生产环境中使用CA颁发的证书

我们可以使用openssl生成一对密钥和证书。通常,证书文件(.crt)包含公钥和证书信息,而.key文件是私钥。

我们可以使用以下步骤:

注意:

方法一:生成自签名证书(一步完成)

# 生成私钥和自签名证书(有效期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"

方法二:分步生成(更灵活)

# 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

[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

执行生成命令:

openssl req -new -x509 -days 365 -nodes \
  -config cert.conf \
  -newkey rsa:2048 \
  -keyout server.key \
  -out server.crt

常用参数说明

验证生成的证书

# 查看证书信息
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值应该相同

安全提示

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文