OpenSSL 自签证书

使用 OpenSSL 1.1.1 + 生成带 SAN 的自签名证书

  • 1、检查 OpenSSL 版
    确保使用 OpenSSL 1.1.1 或更高版本,旧版本可能不支持 -addext。
    openssl version
  • 2、生成带 SAN 的自签名证书(而非 CSR)
    # 格式
    # openssl req -x509 -newkey rsa:4096 -nodes -sha256 -keyout key.pem -days 36500 -out domain.crt -subj "/C=<国家代号>/ST=<省份>/L=<城市>/O=<公司/组织>/CN=<你的域名>"  -addext "subjectAltName = DNS:<你的域名>"
    openssl req -x509 -newkey rsa:4096 -nodes -sha256 -keyout key.pem -out cert.pem -days 3650 -subj "/C=CN/ST=Hangzhou/L=Hangzhou/O=Example Inc./CN=example.com" -addext "subjectAltName=DNS:example.com"
    • 参数说明
      • -req:生成证书签名请求(CSR)或自签名证书
      • -x509:直接生成自签名证书,跳过证书签名请求(CSR)阶段
      • -newkey rsa:4096 :创建新 RSA 密钥(4096 位)
      • -nodes:不加密私钥(即不设置密码保护)
      • -sha256:使用SHA-256哈希算法
      • -keyout:指定私钥输出文件
      • -out:指定自签名证书(非 CSR)输出文件
      • -days 3650:证书有效期为10年
      • -subj:指定证书主题信息。
      • -addext:添加扩展字段(如SAN)。
  • 3、验证自签名证书的主题信息
    openssl x509 -in cert.pem -noout -subject -issuer

使用 OpenSSL + 配置文件 生成带 SAN 的自签名证书

  • 1、生成 4096 位的 RSA 私钥
    openssl genrsa -out private.key 4096
    # 从私钥提取公钥
    # openssl rsa -in private.key -pubout -out public.key
  • 2、生成证书签名请求(CSR)
    # openssl req -new -key private.key -keyout key.pem -out csr.pem -subj "/C=<国家代号>/ST=<省份>/L=<城市>/O=<公司/组织>/CN=<你的域名>"  -addext "subjectAltName = DNS:<你的域名>"
    openssl req -new -key private.key -keyout key.pem -out csr.pem -subj "/C=CN/ST=Hangzhou/L=Hangzhou/O=Example Inc./CN=example.com"
    • 参数说明
      • -req:生成证书签名请求(CSR)或自签名证书
      • -new:生成新的CSR
      • -key:使用现有私钥文件生成CSR
      • -keyout:指定私钥输出文件
      • -out:指定签名请求(CSR)输出文件
      • -subj:指定证书主题信息。
  • 3、通过配置文件(如:extfile.cnf)替代 -addext 参数。创建扩展文件 extfile.cnf
    echo "subjectAltName = DNS:example.com" > extfile.cnf
  • 4、通过 CSR 生成自签名证书
    openssl x509 -req -in csr.pem -out cert.pem -signkey private.key -days 3650 -extfile extfile.cnf
    • 参数说明
      • -req:生成证书签名请求(CSR)或自签名证书
      • -in:指定输入CSR文件(证书签名请求)
      • -new:生成新的CSR
      • -out:指定自签名证书(非 CSR)输出文件
      • -signkey:指定私钥文件签名证书(自签名)
      • -days 3650:证书有效期为10年
      • -extfile extfile.cnf:读取扩展配置文件(如SAN扩展)
  • 5、验证自签名证书的主题信息
    openssl x509 -in cert.pem -noout -subject -issuer
作者:Jeebiz  创建时间:2025-12-10 10:51
最后编辑:Jeebiz  更新时间:2025-12-10 11:49