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

相关推荐
詹某某34112 小时前
什么是 IP SSL 证书?该如何申请
服务器·https·ssl
skywalk81632 小时前
cbsd的clonos/control-pane web管理页面一直闪烁和网页打开显示500error 的问题解决(500error问题未解决)
服务器·前端·freebsd·cbsd
是垚不是土2 小时前
基于OpenTelemetry实现分布式链路追踪
java·运维·分布式·目标跟踪·系统架构
2501_945837432 小时前
火山引擎边缘云服务器,AI+5G协同赋能实时场景
服务器
egoist20232 小时前
[linux仓库]线程池(单例模式)、线程安全与重入、死锁[线程·拾]
linux·单例模式·饿汉模式·懒汉模式·线程安全·死锁·重入问题
weixin_436525072 小时前
若依多租户版 - modules中创建子模块
java·服务器·前端
EverydayJoy^v^2 小时前
RH134简单知识点——第8章——管理存储堆栈
linux·运维·5g
板面华仔2 小时前
Linux基础(下)——工作中常用命令总结
linux·运维·服务器
刃神太酷啦2 小时前
Linux 基础 IO 收官:库的构建与使用、进程地址空间及核心知识点全解----《Hello Linux!》(11)
java·linux·c语言·数据库·c++·算法·php