MENU

证书

• 2023 年 06 月 01 日 • Linux

How to generate a self-signed SSL certificate using OpenSSL?

k3s certificate

自建 CA 中心并签发 CA 证书 - 云物互联 - 博客园 (cnblogs.com)

使用 openssl 生成证书(含openssl详解)

OpenSSL生成根证书CA及签发子证书

那些证书相关的玩意儿(SSL,X.509,PEM,DER,CRT,CER,KEY,CSR,P12等)【CSR文件 和 PEM 文件什么区别】

openssl ca(签署和自建CA)

1. 前置知识

  • 对称加密:用相同的密码进行加密加密
  • 公钥和私钥:数字证书采用公钥体制,用一对互相匹配的密钥进行加密、解密。用户自己设定一把特定的仅为本人所知的私钥,用它进行解密和签名,同时设定一把公公钥并由本人公开,为一组用户所共享,用于加密和验证签名。
  • 非对称加密:著名非对称加密的算法有 RSA , DSA 。 RSA 可以用于加/解密,也可以用于签名验签, DSA 只能用于加密。

1.1 PKI

PKI(Public Key Infrastructure,公钥基础设施),是一种遵循既定标准的密钥管理平台,它能够为所有网络应用提供加密和数字签名等密码服务及所必需的密钥和证书管理体系。简单来说,PKI 就是利用公钥理论和技术建立的提供安全服务的基础设施。PKI 技术是信息安全技术的核心,也是电子商务的关键和基础技术。PKI 既不是一个协议,也不是一个软件,它是一个标准,在这个标准之下发展出的为了实现安全基础服务目的的技术统称为 PKI。

1.2 CA 认证中心(证书签发)

CA(Certificate Authority,证书授权中心)是 PKI 的 “核心”,负责管理和签发证书的第三方机构。一般来说,CA 必须是所有行业和所有公众都信任的、认可的。它负责管理 PKI 下的所有用户(包括各种应用程序)的证书,把用户的公钥和用户的其他信息捆绑在一起,并在网上验证用户身份。除此之外,CA 还要负责用户证书的黑名单登记和黑名单发布。简单来说,CA 的核心功能就是 “发放” 和 “管理” 数字证书。

1.3 X.509 标准

X.509 定义了公钥证书的基本(信息,数据)结构,是国际电信联盟-电信(ITU-T)部分标准和国际标准化组织(ISO)证书格式标准。作为 ITU-ISO 目录服务系列标准的一部分,X.509 是定义了公钥证书结构的基本标准。1988 年首次发布,1993 年和 1996 年两次修订。当前使用的版本是 X.509 V3,它加入了扩展字段支持,这极大地增进了证书的灵活性。X.509 V3 证书包括一组按预定义顺序排列的强制字段,还有可选扩展字段,即使在强制字段中,X.509 证书也允许很大的灵活性,因为它为大多数字段提供了多种编码方案。X.509 V4 版已经推出。

X.509 标准在 PKI 中起到了举足轻重的作用,PKI 由小变大,由原来网络封闭环境到分布式开放环境,X.509 起了很大作用,可以说 X.509 标准是 PKI 的雏形。

PKI 是在 X.509 标准基础上发展起来的

  • SSL 公钥证书
  • 证书废除列表 CRL(Certificate revocation lists,证书黑名单)

1.4 证书

PKI 的目的是使用公钥机制加密技术来保护通信的安全,而公钥算法涉及到很多的加密参数,同时 PKI 机制中还有对用户身份的识别的功能。为了满足这些需求,“证书” 就很自然的出现了。证书本质上是一个 ASCII 文本文件,它仅是将整个公钥机制中需要用到的各种数据都打包到一起,进行统一管理和分发。

1.4.1 SSL 公钥基本结构

1. 证书版本号(Version)
版本号指明X.509证书的格式版本,现在的值可以为:
    1) 0: v1
    2) 1: v2
    3) 2: v3
也为将来的版本进行了预定义

2. 证书序列号(Serial Number)
序列号指定由CA分配给证书的唯一的"数字型标识符"。当证书被取消时,实际上是将此证书的序列号放入由CA签发的CRL中,这也是序列号唯一的原因。

3. 签名算法标识符(Signature Algorithm)
签名算法标识用来指定由CA签发证书时所使用的"签名算法"。算法标识符用来指定CA签发证书时所使用的:
    1) 公开密钥算法
    2) hash算法
example: sha1WithRSAEncryption
须向国际知名标准组织(如ISO)注册

4. 签发机构名(Issuer)
此域用来标识签发证书的CA的X.500 DN(DN-Distinguished Name)名字。包括:
    1) 国家(C)
    2) 省市(ST)
    3) 地区(L)
    4) 组织机构(O)
    5) 单位部门(OU)
    6) 通用名(CN)
    7) 邮箱地址

5. 有效期(Validity)
指定证书的有效期,包括:
    1) 证书开始生效的日期时间
    2) 证书失效的日期和时间
每次使用证书时,需要检查证书是否在有效期内。

6. 证书用户名(Subject)
指定证书持有者的X.500唯一名字。包括:
    1) 国家(C)
    2) 省市(ST)
    3) 地区(L)
    4) 组织机构(O)
    5) 单位部门(OU)
    6) 通用名(CN)
    7) 邮箱地址

7. 证书持有者公开密钥信息(subject PublicKey Info)
证书持有者公开密钥信息域包含两个重要信息:
    1) 证书持有者的公开密钥的值
    2) 公开密钥使用的算法标识符。此标识符包含公开密钥算法和hash算法。
    
8. 扩展项(extension)
X.509 V3证书是在v2的基础上一标准形式或普通形式增加了扩展项,以使证书能够附带额外信息。标准扩展是指由X.509 V3版本定义的对V2版本增加的具有广泛应用前景的扩展项,任何人都
可以向一些权威机构,如ISO,来注册一些其他扩展,如果这些扩展项应用广泛,也许以后会成为标准扩展项。

9. 签发者唯一标识符(Issuer Unique Identifier)
签发者唯一标识符在第2版加入证书定义中。此域用在当同一个X.500名字用于多个认证机构时,用一比特字符串来唯一标识签发者的X.500名字。可选。

10.  证书持有者唯一标识符(Subject Unique Identifier)
持有证书者唯一标识符在第2版的标准中加入X.509证书定义。此域用在当同一个X.500名字用于多个证书持有者时,用一比特字符串来唯一标识证书持有者的X.500名字。可选。

11.  签名算法(Signature Algorithm)
证书签发机构对证书上述内容的签名算法
example: sha1WithRSAEncryption

12.  签名值(Issuer's Signature)
证书签发机构对证书上述内容的签名值

示例:

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            b9:cb:1f:9a:a1:8a:cc:5d
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=Denial, L=Springfield, O=Dis, CN=www.example.com
        Validity
            Not Before: Nov  9 07:27:51 2018 GMT
            Not After : Nov  9 07:27:51 2019 GMT
        Subject: C=US, ST=Denial, L=Springfield, O=Dis, CN=www.example.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:cc:35:81:fb:bd:0b:85:27:c3:fc:1e:91:74:b6:
                    aa:9e:12:8c:8f:f3:53:83:77:13:cf:e0:ae:af:9f:
                    17:7d:6d:d4:27:b4:3c:27:72:2a:45:68:10:c6:6b:
                    67:53:77:15:8f:b7:2d:f3:33:ab:a1:e7:a2:02:a2:
                    a4:92:00:a1:e6:1e:37:23:ca:b4:5a:40:e6:09:42:
                    a0:6c:5b:fa:6d:15:93:13:3a:95:a1:e6:3a:e7:fb:
                    5e:32:ab:d0:3a:fb:63:2f:2f:18:68:a0:8f:10:77:
                    d9:a1:4d:a3:6e:89:41:b5:45:94:5e:32:f9:c8:36:
                    08:99:b8:aa:b5:73:56:da:21:67:6e:f1:51:b8:ad:
                    ce:7b:4e:06:97:92:f8:38:e9:dd:38:bd:88:b6:04:
                    59:0b:1b:a6:c9:0a:c8:49:8d:84:3f:44:a9:72:2e:
                    bf:4c:48:21:4b:f5:3f:ef:9f:5c:90:9f:ab:f3:fb:
                    c9:20:bc:e3:e8:e6:79:c5:75:1a:45:61:ed:47:ec:
                    56:22:52:94:40:4c:8b:ab:7a:ab:6d:68:ed:e6:09:
                    e3:4f:ef:f3:0e:8c:34:6e:6b:94:21:a1:72:d7:c5:
                    ce:d1:61:f0:bb:13:1d:1c:bf:b4:aa:64:e2:fd:a8:
                    3c:9b:17:9c:df:9d:9b:4e:84:5f:b1:df:d9:22:19:
                    e1:45
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                73:D4:B6:E1:C9:5D:B9:CE:70:91:05:07:A3:C4:9C:2D:FD:EE:B8:A3
            X509v3 Authority Key Identifier:
                keyid:73:D4:B6:E1:C9:5D:B9:CE:70:91:05:07:A3:C4:9C:2D:FD:EE:B8:A3

            X509v3 Basic Constraints:
                CA:TRUE
    Signature Algorithm: sha256WithRSAEncryption
         4a:d2:d0:9e:a6:7e:21:25:d7:20:4b:8d:98:0e:52:15:2d:90:
         d0:bc:45:68:90:72:10:41:b2:40:3c:5d:bb:d4:32:b9:6a:ba:
         a6:95:63:4a:1e:8c:0c:f3:7e:03:d8:4b:57:f5:e8:23:49:ae:
         a7:56:22:49:fc:ee:5c:a9:73:75:06:78:a1:14:75:f1:fa:79:
         b6:7c:89:bc:ec:38:fa:0b:9f:32:0c:47:86:9e:30:3c:85:ae:
         5e:0f:5a:62:a0:b6:51:64:c4:ab:ed:f1:be:78:ff:a9:c1:6e:
         93:4c:79:a8:4b:cd:b8:29:fb:ea:df:4d:e5:09:a9:54:69:89:
         56:a4:d2:1b:74:2c:a7:6c:ac:24:34:3d:9c:1d:6c:c6:64:82:
         71:d5:cc:a7:3e:c3:a6:ae:32:19:bc:29:bb:9b:15:ad:cd:c0:
         67:20:6e:14:2b:9a:fb:82:32:30:84:73:04:65:49:3a:17:48:
         1e:e7:7d:92:e9:fb:9e:71:f0:11:48:39:18:09:7e:4e:62:cb:
         9a:90:6a:fb:27:1f:4c:f4:ac:6b:9b:4c:a7:86:e0:7d:e9:8e:
         d2:f2:d0:ec:f3:09:a7:60:ad:73:0b:1a:db:e1:21:57:cf:3d:
         22:f3:e0:be:e2:67:5d:ea:73:dd:90:7a:dc:47:ea:9f:f7:7d:
         72:e8:25:87

1.5 证书签发过程

  • 服务端向第三方 CA 机构提交公钥、组织信息、个人信息等信息并申请认证;
  • CA 机构通过线上、线下等多种手段验证申请者提供信息的真实性,如:组织是否存在、企业是否合法,是否拥有域名的所有权等;
  • 信息审核通过,CA 会向申请者签发认证文件-证书。证书包含以下信息:申请者基本信息的明文(包含公钥、申请者的组织信息和个人信息、签发机构 CA 的信息、有效时间、证书序列号的内容文),和一个签名(CA 使用散列函数计算公开的明文信息的信息摘要,然后,采用 CA 的私钥对信息摘要进行加密,密文即 “签名”);
  • 客户端向服务端发出请求时,服务端响应证书文件给客户端;
  • 客户端读取证书中的相关的明文信息,采用相同的散列函数计算得到信息摘要,然后,利用对应 CA 的公钥解密签名数据,对比证书的信息摘要,如果一致,则可以确认证书的合法性,即公钥合法;
  • 客户端然后验证证书相关的域名信息、有效时间等信息;
  • 客户端会内置信任 CA 的证书信息(包含公钥),如果 CA 不被信任,则找不到对应 CA 的证书,证书也会被判定非法。
证书 = 公钥 + 申请者与颁发者信息 + 签名

简单的非对称加密系统中,客户端只需要获得服务器发放的公钥即可访问服务端。CA 体系下的客户端则需要获得 CA 机构签发的服务器证书以及 CA 机构的公钥,首先验证证书的可靠性之后才能获得服务端的公钥,继而访问服务端。

1.6 自建 CA 签发证书并认证 HTTPS 网站的过

  • CA 机构生成私钥 ca.key ;
  • CA 机构使用私钥 ca.key 加密自己的组织信息(域名/组织 etc.),生成 ca.csr 文件;
  • CA 机构使用自己的私钥 ca.key 和自己的证书请求文件为自己颁发 ca.crt 证书文件;
  • 网站(Server 端)生成私钥 server.key ;
  • 网站使用私钥 server.key 加密网站信息(域名/组织 etc.)生成证书请求文件 server.csr ,并提交到 CA 机构;
  • CA 机构使用自己的私钥 ca.key 和根证书 ca.crt 签发网站证书 server.crt ;
  • 网站配置 Apache/Nginx 加载 server.key 和 server.crt 并运行 HTTPS 模块
  • 用户首次通过浏览器访问网站,网站首先返回 server.crt,由于 server.cer 使用 CA 机构的私钥签发,因此可以通过保存在用户本地的CA 机构根证书 ca.crt 进行验证。
  • 用户验证 server.crt 和 ca.crt 的有效性。如果验证通过,则得到网站的公钥并以此访问网站;否则,提示用户风险信息
  • 用户通过网站的公钥与网站交换对称加密共享密钥,进行正式的 SSL 会话

所以,用户能够与网站建立 SSL 通信的关键在于用户是否拥有 CA 机构的根证书 ca.crt 和网站证书 server.crt。 用户拿着 ca.crt 与 server.crt 验证,只有通过后,用户才可以获得网站真实的公钥。

2. 自建 CA 签发证书流程

2.1 签发 CA 根证书

2.1.1 生成 CA 根证私钥书 pem 文件

命令解释

[root@server ~]# openssl genrsa -h
Usage: genrsa [options] numbits

General options:
 -help               Display this summary
 -engine val         Use engine, possibly a hardware device

Input options:
 -3                  (deprecated) Use 3 for the E value
 -F4                 Use the Fermat number F4 (0x10001) for the E value
 -f4                 Use the Fermat number F4 (0x10001) for the E value

Output options:
 -out outfile        Output the key to specified file
 -passout val        Output file pass phrase source
 -primes +int        Specify number of primes
 -verbose            Verbose output
 -traditional        Use traditional format for private keys
 -*                  Encrypt the output with any supported cipher

Random state options:
 -rand val           Load the given file(s) into the random number generator
 -writerand outfile  Write random data to the specified file

Provider options:
 -provider-path val  Provider load path (must be before 'provider' argument if required)
 -provider val       Provider to load (can be specified multiple times)
 -propquery val      Property query used when fetching algorithms

Parameters:
 numbits             Size of key in bits
 

example 生成一个1024位的RSA私钥,并用3DES加密(密码为1111),保存为server.key文件
openssl genrsa -out server.key -passout pass:1111 -des3 1024 

案例:

openssl genrsa \
    -out ca.key \
    4096

# 使用 AES256 加密私钥
openssl genrsa \
    -aes256 \
    -passout pass:1111 \
    -out ca.key \
    4096

2.1.2 生成证书签名请求(CSR)

证书请求文件(Certificate Signing Request) 常见后缀名为 csr 。此文件不是证书,而是向权威证书颁发机构获得签名证书的请求文件,其核心内容是一个公钥和申请者的基本信息(例如:国家地区,网址等内容)

[root@server ~]# openssl req -h
Usage: req [options]

General options:
 -help                 Display this summary
 -engine val           Use engine, possibly a hardware device
 -keygen_engine val    Specify engine to be used for key generation operations
 -in infile            X.509 request input file (default stdin)
 -inform PEM|DER       Input format - DER or PEM
 -verify               Verify self-signature on the request

Certificate options:
 -new                  New request
 -config infile        Request template file
 -section val          Config section to use (default "req")
 -utf8                 Input characters are UTF8 (default ASCII)
 -nameopt val          Certificate subject/issuer name printing options
 -reqopt val           Various request text options
 -text                 Text form of request
 -x509                 Output an X.509 certificate structure instead of a cert request
 -CA infile            Issuer cert to use for signing a cert, implies -x509
 -CAkey val            Issuer private key to use with -CA; default is -CA arg
                       (Required by some CA's)
 -subj val             Set or modify subject of request or cert
 -subject              Print the subject of the output request or cert
 -multivalue-rdn       Deprecated; multi-valued RDNs support is always on.
 -days +int            Number of days cert is valid for
 -set_serial val       Serial number to use
 -copy_extensions val  copy extensions from request when using -x509
 -addext val           Additional cert extension key=value pair (may be given more than once)
 -extensions val       Cert extension section (override value in config file)
 -reqexts val          Request extension section (override value in config file)
 -precert              Add a poison extension to the generated cert (implies -new)

Keys and Signing options:
 -key val              Key for signing, and to include unless -in given
 -keyform format       Key file format (ENGINE, other values ignored)
 -pubkey               Output public key
 -keyout outfile       File to write private key to
 -passin val           Private key and certificate password source
 -passout val          Output file pass phrase source
 -newkey val           Generate new key with [<alg>:]<nbits> or <alg>[:<file>] or param:<file>
 -pkeyopt val          Public key options as opt:value
 -sigopt val           Signature parameter in n:v form
 -vfyopt val           Verification parameter in n:v form
 -*                    Any supported digest

Output options:
 -out outfile          Output file
 -outform PEM|DER      Output format - DER or PEM
 -batch                Do not ask anything during request generation
 -verbose              Verbose output
 -noenc                Don't encrypt private keys
 -nodes                Don't encrypt private keys; deprecated
 -noout                Do not output REQ
 -newhdr               Output "NEW" in the header lines
 -modulus              RSA modulus

Random state options:
 -rand val             Load the given file(s) into the random number generator
 -writerand outfile    Write random data to the specified file

Provider options:
 -provider-path val    Provider load path (must be before 'provider' argument if required)
 -provider val         Provider to load (can be specified multiple times)
 -propquery val        Property query used when fetching algorithms
 

example1 利用CA的RSA密钥创建一个自签署的CA证书(X.509结构)
openssl req -new -x509 -days 3650 -key server.key -out ca.crt 

example2 用server.key生成证书签署请求CSR(这个CSR用于之外发送待CA中心等待签发)
openssl req -new -key server.key -out server.csr

example3 查看CSR的细节:
openssl req -noout -text -in server.csr

案例:

使用上一步生成的私钥文件生成证书请求文件

# 次操作需要交互输入请求者几本信息
openssl req \
    -new \
    -config openssl.cnf \
    -extensions v3_ca \
    -key ca.key \
    -out ca.csr

# 指定
openssl req \
    -new \
    -key ca.key \
    -config openssl.cnf \
    -extensions v3_ca \
    -out ca.csr \
    -subj "/C=CN/ST=ShangHai/L=ShangHai/O=whg/CN=cn.whg.*"

注意:这里用到俩个特殊参数,分别是 -config openssl.cnf 加载 openssl 配置文件,和 -extensions v3_ca 启用配置文件中的 v3_ca 扩展配置。如果没有该文件可以直接复制 openssl.cnf 作为默认配置。

2.1.3 自签发根证书

证书文件(Certificate)后缀名一般为 crtcer。前常见于 Linux 后者常见于 Windows。文件可以是 PEMDER 编码。

使用 CA 的私钥 ca.key 和 CA 的证书请求文件自签发根证书:

[root@server ~]# openssl x509 -h
Usage: x509 [options]

General options:
 -help                      Display this summary
 -in infile                 Certificate input, or CSR input file with -req (default stdin)
 -passin val                Private key and cert file pass-phrase source
 -new                       Generate a certificate from scratch
 -x509toreq                 Output a certification request (rather than a certificate)
 -req                       Input is a CSR file (rather than a certificate)
 -copy_extensions val       copy extensions when converting from CSR to x509 or vice versa
 -inform format             CSR input file format (DER or PEM) - default PEM
 -vfyopt val                CSR verification parameter in n:v form
 -key val                   Key for signing, and to include unless using -force_pubkey
 -signkey val               Same as -key
 -keyform PEM|DER|ENGINE    Key input format (ENGINE, other values ignored)
 -out outfile               Output file - default stdout
 -outform format            Output format (DER or PEM) - default PEM
 -nocert                    No cert output (except for requested printing)
 -noout                     No output (except for requested printing)

Certificate printing options:
 -text                      Print the certificate in text form
 -dateopt val               Datetime format used for printing. (rfc_822/iso_8601). Default is rfc_822.
 -certopt val               Various certificate text printing options
 -fingerprint               Print the certificate fingerprint
 -alias                     Print certificate alias
 -serial                    Print serial number value
 -startdate                 Print the notBefore field
 -enddate                   Print the notAfter field
 -dates                     Print both notBefore and notAfter fields
 -subject                   Print subject DN
 -issuer                    Print issuer DN
 -nameopt val               Certificate subject/issuer name printing options
 -email                     Print email address(es)
 -hash                      Synonym for -subject_hash (for backward compat)
 -subject_hash              Print subject hash value
 -subject_hash_old          Print old-style (MD5) subject hash value
 -issuer_hash               Print issuer hash value
 -issuer_hash_old           Print old-style (MD5) issuer hash value
 -ext val                   Restrict which X.509 extensions to print and/or copy
 -ocspid                    Print OCSP hash values for the subject name and public key
 -ocsp_uri                  Print OCSP Responder URL(s)
 -purpose                   Print out certificate purposes
 -pubkey                    Print the public key in PEM format
 -modulus                   Print the RSA key modulus

Certificate checking options:
 -checkend intmax           Check whether cert expires in the next arg seconds
                            Exit 1 (failure) if so, 0 if not
 -checkhost val             Check certificate matches host
 -checkemail val            Check certificate matches email
 -checkip val               Check certificate matches ipaddr

Certificate output options:
 -set_serial val            Serial number to use, overrides -CAserial
 -next_serial               Increment current certificate serial number
 -days int                  Number of days until newly generated certificate expires - default 30
 -preserve_dates            Preserve existing validity dates
 -subj val                  Set or override certificate subject (and issuer)
 -force_pubkey infile       Place the given key in new certificate
 -clrext                    Do not take over any extensions from the source certificate or request
 -extfile infile            Config file with X509V3 extensions to add
 -extensions val            Section of extfile to use - default: unnamed section
 -sigopt val                Signature parameter, in n:v form
 -badsig                    Corrupt last byte of certificate signature (for test)
 -*                         Any supported digest, used for signing and printing

Micro-CA options:
 -CA infile                 Use the given CA certificate, conflicts with -key
 -CAform PEM|DER            CA cert format (PEM/DER/P12); has no effect
 -CAkey val                 The corresponding CA key; default is -CA arg
 -CAkeyform PEM|DER|ENGINE  CA key format (ENGINE, other values ignored)
 -CAserial val              File that keeps track of CA-generated serial number
 -CAcreateserial            Create CA serial number file if it does not exist

Certificate trust output options:
 -trustout                  Mark certificate PEM output as trusted
 -setalias val              Set certificate alias (nickname)
 -clrtrust                  Clear all trusted purposes
 -addtrust val              Trust certificate for a given purpose
 -clrreject                 Clears all the prohibited or rejected uses of the certificate
 -addreject val             Reject certificate for a given purpose

Random state options:
 -rand val                  Load the given file(s) into the random number generator
 -writerand outfile         Write random data to the specified file
 -engine val                Use engine, possibly a hardware device

Provider options:
 -provider-path val         Provider load path (must be before 'provider' argument if required)
 -provider val              Provider to load (can be specified multiple times)
 -propquery val             Property query used when fetching algorithms

案例:

openssl x509 \
    -req \
    -days 3650 \
    -sha256 \
    -sha1 \
    -extfile openssl.cnf \
    -extensions v3_ca \
    -signkey ca.key \
    -in ca.csr \
    -out ca.crt

2.1.4 一键命令

openssl req \
    -x509 \
    -nodes \
    -newkey rsa:4096 \
    -sha256 \
    -config openssl.cnf \
    -extensions v3_ca \
    -days 36500 \
    -subj "/C=CN/ST=ShangHai/L=ShangHai/O=whg/CN=cn.whg.*" \
    -keyout ca.key \
    -out ca.crt
  • req 生成证书请求命令
  • x509 输出 x509 格式证书
  • days 证书有效期
  • nodes 私钥不加密
  • newkey 生成私钥格式为 RSA ,加密长度为 2048
  • keyout 私钥输出路径
  • out 证书输出路径
  • subj 证书拥有者信息。如果不加该选择,会交互提示输入。

2.2 签发 Server 证书

在网站使用时,需要根据具体域名签发对应的网站证书。域名需需要包含在证书请求文件中。

2.2.1 生成服务端私钥

openssl genrsa -aes256 -nodes -out server.key 1024

2.2.2 生成证书请求文件
证书请求文件包含申请者公钥和基本信息。该文件可以直接提交给权威 CA 机构签发证书,也可以使用上面自建 CA 机构签发私有证书。

openssl req \
    -new \
    -config openssl.cnf \
    -extensions v3_req \
    -key server.key \
    -subj "/C=CN/ST=ShangHai/L=ShangHai/O=whg/CN=cn.whg.server"
    -out server.csr \

注意:这里加载了 openssl.cnf 配置文件,但使用了 v3_req 扩展用来生成服务证书,而不是根证书。

2.2.3 用根证书签发服务端证书

openssl x509 -req \
    -days 365 \
    -sha256 \
    -extfile openssl.cnf \
    -extensions v3_req \
    -CA ca.crt \
    -CAkey cakey.key \
    -in server.csr \
    -out server.crt

说明:

  • CA 指定 CA 根证书路径
  • CAkey 指定 CA 根证书私钥路径

2.2.4 一键命令

生成不加密密和证书请求文件

注意: subj 参数不能放到最后,要不然生成文件的时候读不到该参数

openssl req \
    -nodes \
    -newkey rsa:4096 \
    -sha256 \
    -config openssl.cnf \
    -extensions v3_req \
    -keyout server_whg.key \
    -subj "/C=CN/ST=ShangHai/L=ShangHai/O=whg/CN=cn.whg.server" \
    -out server_whg.csr

用 CA 证书签发证书

openssl x509 \
    -req \
    -days 365 \
    -extfile openssl.cnf \
    -extensions v3_req \
    -in server_whg.csr \
    -CA ca.crt \
    -CAkey ca.key \
    -CAcreateserial \
    -out server_whg.crt

2.3 用根证书签发 Client 证书

生成客户端私钥

openssl genrsa \
    -aes256 \
    -out client.key \
    4096

2.3.1 生成客户端证书请求文件

openssl req \
    -new \
    -sha256 \
    -config openssl.cnf \
    -extensions v3_req \
    -key client.key \
    -out client.csr \
    -subj "/C=CN/ST=ShangHai/L=ShangHai/O=whg/CN=cn.whg.client"

2.3.2 使用根证书签发客户端证书

openssl x509 \
    -req \
    -days 365 \
    -sha256 \
    -extfile openssl.cnf \
    -extensions v3_req \
    -CA ca.crt \
    -CAkey cakey.key \
    -in client.csr \
    -out client.crt

3. 查看证书

openssl x509 -text -in client.crt

# 使用 -inform der 指定证书格式
openssl x509 -text -inform der -in client.crt 

4. 导出证书

4.1 导出客户端证书

[root@server ~]# openssl pkcs12 -h
Usage: pkcs12 [options]

General options:
 -help               Display this summary
 -in infile          Input file
 -out outfile        Output file
 -passin val         Input file pass phrase source
 -passout val        Output file pass phrase source
 -password val       Set PKCS#12 import/export password source
 -twopass            Separate MAC, encryption passwords
 -nokeys             Don't output private keys
 -nocerts            Don't output certificates
 -noout              Don't output anything, just verify PKCS#12 input
 -legacy             Use legacy encryption: 3DES_CBC for keys, RC2_CBC for certs
 -engine val         Use engine, possibly a hardware device

Provider options:
 -provider-path val  Provider load path (must be before 'provider' argument if required)
 -provider val       Provider to load (can be specified multiple times)
 -propquery val      Property query used when fetching algorithms

Random state options:
 -rand val           Load the given file(s) into the random number generator
 -writerand outfile  Write random data to the specified file

PKCS#12 import (parsing PKCS#12) options:
 -info               Print info about PKCS#12 structure
 -nomacver           Don't verify integrity MAC
 -clcerts            Only output client certificates
 -cacerts            Only output CA certificates
 -*                  Any supported cipher for output encryption
 -noenc              Don't encrypt private keys
 -nodes              Don't encrypt private keys; deprecated

PKCS#12 output (export) options:
 -export             Create PKCS12 file
 -inkey val          Private key, else read from -in input file
 -certfile infile    Extra certificates for PKCS12 output
 -passcerts val      Certificate file pass phrase source
 -chain              Build and add certificate chain for EE cert,
                     which is the 1st cert from -in matching the private key (if given)
 -untrusted infile   Untrusted certificates for chain building
 -CAfile infile      PEM-format file of CA's
 -CApath dir         PEM-format directory of CA's
 -CAstore uri        URI to store of CA's
 -no-CAfile          Do not load the default certificates file
 -no-CApath          Do not load certificates from the default certificates directory
 -no-CAstore         Do not load certificates from the default certificates store
 -name val           Use name as friendly name
 -caname val         Use name as CA friendly name (can be repeated)
 -CSP val            Microsoft CSP name
 -LMK                Add local machine keyset attribute to private key
 -keyex              Set key type to MS key exchange
 -keysig             Set key type to MS key signature
 -keypbe val         Private key PBE algorithm (default AES-256 CBC)
 -certpbe val        Certificate PBE algorithm (default PBES2 with PBKDF2 and AES-256 CBC)
 -descert            Encrypt output with 3DES (default PBES2 with PBKDF2 and AES-256 CBC)
 -macalg val         Digest algorithm to use in MAC (default SHA1)
 -iter +int          Specify the iteration count for encryption and MAC
 -noiter             Don't use encryption iteration
 -nomaciter          Don't use MAC iteration)
 -maciter            Unused, kept for backwards compatibility
 -nomac              Don't generate MAC
openssl pkcs12 \
    -export \
    -clcerts \
    -name myclient \
    -inkey client.pem \
    -in client.crt \
    -out client.keystore

说明:

  • pkcs12 用来处理 pkcs#12 格式的证书
  • export 导出操作
  • clcerts 导出的是客户端证书
  • cacerts 导出的是 CA 证书
  • name 导出证书别名
  • in 要导出证书的路径
  • out 输出的密钥文件路径

4.2 导出服务端证书

openssl pkcs12 \
    -export \
    -clcerts \
    -name myserver \
    -inkey server.pem \
    -in server.crt \
    -out server.keystore

4.3 导出信任证书

keytool -importcert \
    -trustcacerts \
    -alias www.mydomain.com \
    -file ca.crt \
    -keystore ca-trust.keystore

5. 证书编码转换

PEM --> DER

openssl x509 -in cert.crt -outform der -out cert.der

DER --> PEM

openssl x509 -in cert.crt -inform der -outform pem -out cert.pem