温馨提示×

Linux openssl如何配置证书

小樊
41
2026-08-25 07:33:39
栏目: 云计算

在 Linux 上用 OpenSSL 配置证书,常见场景有:
✅ 自签名证书(测试/内网)
✅ CA 签发证书(更规范)
✅ Nginx / Apache 使用证书
下面按最常用流程一步步说明。


一、安装 OpenSSL

# Debian / Ubuntu
sudo apt update
sudo apt install openssl

# CentOS / Rocky / Alma
sudo yum install openssl

检查版本:

openssl version

二、生成自签名证书(最简单)

1️⃣ 生成私钥

openssl genrsa -out server.key 2048

2️⃣ 生成自签名证书(CRT)

openssl req -new -x509 -key server.key -out server.crt -days 365

交互式填写:

  • Country Name:CN
  • Common Name:域名或 IP(非常重要)

✅ 适合:

  • 本地开发
  • 内网服务
  • 测试 HTTPS

三、生成 CA 并签发证书(推荐生产环境)

1️⃣ 创建 CA 私钥和证书

# CA 私钥
openssl genrsa -out ca.key 2048

# CA 证书
openssl req -x509 -new -key ca.key -out ca.crt -days 3650

2️⃣ 生成服务器私钥和请求(CSR)

openssl genrsa -out server.key 2048

openssl req -new -key server.key -out server.csr

⚠️ Common Name 必须填域名或 IP


3️⃣ CA 签发服务器证书

openssl x509 -req \
  -in server.csr \
  -CA ca.crt \
  -CAkey ca.key \
  -CAcreateserial \
  -out server.crt \
  -days 365

四、证书文件说明

文件 作用
.key 私钥(必须保密)
.crt 证书
.csr 证书签名请求
.pem 文本格式证书(可包含 key)

五、Nginx 使用证书示例

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;

    location / {
        root /usr/share/nginx/html;
    }
}

重启:

sudo nginx -t
sudo systemctl restart nginx

六、Apache 使用证书示例

<VirtualHost *:443>
    ServerName example.com

    SSLEngine on
    SSLCertificateFile /etc/httpd/ssl/server.crt
    SSLCertificateKeyFile /etc/httpd/ssl/server.key
</VirtualHost>

七、生成 PFX / PKCS12(Windows / Java 常用)

openssl pkcs12 -export \
  -out server.pfx \
  -inkey server.key \
  -in server.crt \
  -certfile ca.crt

八、常见问题

❓ 浏览器提示不安全

  • 自签名证书 ✅ 解决方法:
  • 导入 CA 证书到系统/浏览器
  • 或使用 Let’s Encrypt

❓ 证书和私钥不匹配

openssl x509 -noout -modulus -in server.crt | md5sum
openssl rsa -noout -modulus -in server.key | md5sum

✅ 两个值必须一致


九、推荐生产方案(公网)

# 使用 Let's Encrypt
sudo apt install certbot
sudo certbot certonly --standalone -d example.com

如果你愿意,可以告诉我:

  • ✅ 用 Nginx / Apache / 其他
  • 内网还是公网
  • ✅ 是否需要 多域名 / SAN

我可以给你完全定制的一套配置命令

0