通过OpenSSL 生成自签名证书

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

我们可以使用以下步骤:

  1. 生成私钥(.key文件)

  2. 使用私钥生成证书签名请求(CSR)

  3. 使用私钥和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

方法三:使用配置文件生成

  1. 创建配置文件 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
  1. 执行生成命令:
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值应该相同

安全提示:

  1. 保护私钥:私钥文件 (.key) 应严格保密

  2. 密码保护 (可选):移除 -nodes 参数可设置私钥密码

  3. 生产环境:自签名证书仅用于测试,生产环境应使用 CA 颁发的证书

  4. 密钥长度:推荐使用 2048 位或以上

相关推荐
未济4 天前
linux 配置环境变量
linux
傲世仙尊4 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
虎头金猫4 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
_艾伦 耶格尔.4 天前
进程间通信
linux
AI职业加油站4 天前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
Liuqy-054 天前
Linux IO编程——静态库、动态库
linux
此冬歌咏4 天前
K8s 节点故障实战:优雅驱逐 31 秒,硬故障 331 秒,以及那个永远 Pending 的 Pod
运维·k8s
彧azz4 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
-梅4 天前
linux(8) 软硬链接
linux·运维·服务器
Wang's Blog4 天前
Java 项目实战: 外卖平台-文件下载与ServletOutputStream回写浏览器
服务器·项目开发