通过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 位或以上

相关推荐
chlk1238 小时前
Linux文件权限完全图解:读懂 ls -l 和 chmod 755 背后的秘密
linux·操作系统
舒一笑8 小时前
Ubuntu系统安装CodeX出现问题
linux·后端
改一下配置文件9 小时前
Ubuntu24.04安装NVIDIA驱动完整指南(含Secure Boot解决方案)
linux
碳基沙盒10 小时前
OpenClaw 多 Agent 配置实战指南
运维
深紫色的三北六号19 小时前
Linux 服务器磁盘扩容与目录迁移:rsync + bind mount 实现服务无感迁移(无需修改配置)
linux·扩容·服务迁移
SudosuBash1 天前
[CS:APP 3e] 关于对 第 12 章 读/写者的一点思考和题解 (作业 12.19,12.20,12.21)
linux·并发·操作系统(os)
哈基咪怎么可能是AI1 天前
为什么我就想要「线性历史 + Signed Commits」GitHub 却把我当猴耍 🤬🎙️
linux·github
十日十行2 天前
Linux和window共享文件夹
linux
Sinclair2 天前
简单几步,安卓手机秒变服务器,安装 CMS 程序
android·服务器
木心月转码ing2 天前
WSL+Cpp开发环境配置
linux