目录

一.手动生成单个ssl证书

1.创建CA和申请证书

二.脚本生成单个CA ssl证书

三.脚本自动生成通配符ssl证书

四.导出证书


一.手动生成单个ssl证书

1.创建CA和申请证书

使用openssl工具创建CA证书和申请证书时,需要先查看配置文件,因为配置文件中对证书的名称和存放位置等相关信息都做了定义,具体可参考 /etc/pki/tls/openssl.cnf 文件。

[root@VM-0-114-centos ~]# vim /etc/pki/tls/openssl.cnf 
####################################################################
[ ca ]
default_ca      = CA_default            # The default ca section

####################################################################
[ CA_default ]

dir             = /etc/pki/CA           # Where everything is kept
certs           = $dir/certs            # Where the issued certs are kept
crl_dir         = $dir/crl              # Where the issued crl are kept
database        = $dir/index.txt        # database index file.
#unique_subject = no                    # Set to 'no' to allow creation of
                                        # several ctificates with same subject.
new_certs_dir   = $dir/newcerts         # default place for new certs.

certificate     = $dir/cacert.pem       # The CA certificate
serial          = $dir/serial           # The current serial number
crlnumber       = $dir/crlnumber        # the current crl number
                                        # must be commented out to leave a V1 CRL
crl             = $dir/crl.pem          # The current CRL
private_key     = $dir/private/cakey.pem# The private key
RANDFILE        = $dir/private/.rand    # private random number file

x509_extensions = usr_cert              # The extentions to add to the cert
# Comment out the following two lines for the "traditional"
# (and highly broken) format.
name_opt        = ca_default            # Subject Name options
cert_opt        = ca_default            # Certificate field options

# Extension copying option: use with caution.
# copy_extensions = copy

# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
# so this is commented out by default to leave a V1 CRL.
# crlnumber must also be commented out to leave a V1 CRL.
# crl_extensions        = crl_ext

default_days    = 365                   # how long to certify for
default_crl_days= 30                    # how long before next CRL
default_md      = sha256                # use SHA-256 by default
preserve        = no                    # keep passed DN ordering

# A few difference way of specifying how similar the request should look
# For type CA, the listed attributes must be the same, and the optional
# and supplied fields are just that :-)
policy          = policy_match

# For the CA policy
[ policy_match ]
countryName             = match
stateOrProvinceName     = match
organizationName        = match
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

(1)、创建自签证书

第一步:创建为 CA 提供所需的目录及文件

[root@VM-0-114-centos CA]# mkdir -pv /etc/pki/CA/{certs,crl,newcerts,private}
[root@VM-0-114-centos CA]# touch /etc/pki/CA/{serial,index.txt}
[root@VM-0-114-centos CA]# tree
.
├── certs
├── crl
├── index.txt
├── newcerts
├── private
└── serial

4 directories, 2 files
第二步:指明证书的开始编号
]# echo 01 >> serial
第三步:生成私钥,私钥的文件名与存放位置要与配置文件中的设置相匹配;
[root@VM-0-114-centos CA]# (umask 077;openssl genrsa -out /etc/pki/CA/private/cakey.pem 4096)
Generating RSA private key, 4096 bit long modulus
.....................................................................................................................................................................................................................++
..........................................................++
e is 65537 (0x10001)
[root@VM-0-114-centos CA]# ll private/
总用量 4
-rw------- 1 root root 3243 10月 18 21:03 cakey.pem
第四步:生成自签证书,自签证书的存放位置也要与配置文件中的设置相匹配,生成证书时需要填写相应的信息;
[root@VM-0-114-centos CA]# openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -out /etc/pki/CA/cacert.pem -days 3650
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:ShengZhen    
Locality Name (eg, city) [Default City]:shenzhen
Organization Name (eg, company) [Default Company Ltd]:keyao
Organizational Unit Name (eg, section) []:mage
Common Name (eg, your name or your server's hostname) []:*.tapd.demo.com
Email Address []:httpd@keyao.com
[root@VM-0-114-centos CA]# ll /etc/pki/CA/cacert.pem 
-rw-r--r-- 1 root root 2118 10月 18 21:11 /etc/pki/CA/cacert.pem
命令中用到的选项解释:
-new:表示生成一个新证书签署请求
-x509:专用于CA生成自签证书,如果不是自签证书则不需要此项
-key:生成请求时用到的私钥文件
-out:证书的保存路径
-days:证书的有效期限,单位是day(天),默认是365天
(2)颁发证书
在需要使用证书的主机上生成证书请求,以 httpd 服务为例,步骤如下:
第一步:在需要使用证书的主机上生成私钥,这个私钥文件的位置可以随意定
第二步:生成证书签署请求
第三步:将请求通过可靠方式发送给 CA 主机
[root@VM-0-114-centos test]# (umask 077;openssl genrsa -out httpd.key 4096)  
Generating RSA private key, 4096 bit long modulus
............................................................................................................................................................................................................................................++
..........................++
e is 65537 (0x10001)
[root@VM-0-114-centos test]# openssl req -new -key httpd.key -out httpd.csr -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:Shenzhen
Locality Name (eg, city) [Default City]:shenzhen
Organization Name (eg, company) [Default Company Ltd]:keyao
Organizational Unit Name (eg, section) []:*.tapd.demo.com
Common Name (eg, your name or your server's hostname) []:www.tapd.demo.com
Email Address []:https@keyao.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@VM-0-114-centos test]# ll
总用量 8
-rw-r--r-- 1 root root 1765 10月 18 21:26 httpd.csr
-rw------- 1 root root 3243 10月 18 21:23 httpd.key
第四步:CA 服务器拿到证书签署请求文件后颁发证书,这一步是在 CA 服务器上做的
[root@VM-0-114-centos /]# ls
bin   dev   lost+found  opt   run   storage  usr
boot  etc   lib        media       proc  sbin  sys      var
data  home  lib64      mnt         root  srv   tmp

[root@VM-0-114-centos /]# openssl ca -in /httpd.csr -out /etc/pki/CA/certs/httpd.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 2 (0x2)
        Validity
            Not Before: Oct 19 13:28:38 2021 GMT
            Not After : Oct 19 13:28:38 2022 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = ShenZhen
            organizationName          = keyao
            organizationalUnitName    = yaoke.com
            commonName                = www.yaoke.com
            emailAddress              = httpd@magedu.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                A7:23:5A:30:09:64:4D:D8:51:3A:BB:C9:B6:E0:F6:80:87:5C:E0:2F
            X509v3 Authority Key Identifier: 
                keyid:36:55:4C:EE:B6:FA:90:67:AF:91:71:77:25:D0:A9:91:54:B3:68:06

Certificate is to be certified until Oct 19 13:28:38 2022 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@VM-0-114-centos /]# ls
bin   dev   httpd.csr  lost+found  opt   run   storage  usr
boot  etc   lib        media       proc  sbin  sys      var
data  home  lib64      mnt         root  srv   tmp
查看证书信息的命令为:
[root@VM-0-114-centos /]# openssl x509 -in /etc/pki/CA/certs/httpd.crt -noout -serial -subject
serial=02
subject= /C=CN/ST=ShenZhen/O=keyao/OU=yaoke.com/CN=www.yaoke.com/emailAddress=httpd@magedu.com
(3)吊销证书
吊销证书的步骤也是在CA服务器上执行的,以刚才新建的 httpd.crt 证书为例,吊销步骤如下:
第一步:在客户机上获取要吊销证书的 serial 和 subject 信息 
第二步:根据客户机提交的 serial 和 subject 信息,对比其余本机数据库 index.txt 中存储的是否一致 
第三步:执行吊销操作
[root@VM-0-114-centos CA]# openssl ca -revoke /etc/pki/CA/newcerts/01.pem 
Using configuration from /etc/pki/tls/openssl.cnf
Revoking Certificate 01.
Data Base Updated
第四步:生成吊销证书的吊销编号 (第一次吊销证书时执行)
]# echo 01 > /etc/pki/CA/crlnumber
第五步:更新证书吊销列表
]# openssl ca -gencrl -out /etc/pki/CA/crl/ca.crl
查看 crl 文件命令:
]# openssl crl -in /etc/pki/CA/crl/ca.crl -noout -text
二.脚本生成单个CA ssl证书
~]#vim aaaCA.cnf
[ req ]
distinguished_name  = req_distinguished_name
x509_extensions     = root_ca

[ req_distinguished_name ]

# 以下内容可随意填写
countryName             = CN (2 letter code)
countryName_min         = 2
countryName_max         = 2
stateOrProvinceName     = Guangdong
localityName            = Shenzhen
0.organizationName      = TC
organizationalUnitName  = technology
0.commonName              = aaa.xxx.co
0.commonName_max          = 64
1.commonName              = aaa.xxx.pro
1.commonName_max          = 64
2.commonName              = aaa.xxx.co
2.commonName_max          = 64
3.commonName              = aaa.xxx.pro
3.commonName_max          = 64
4.commonName              = aaa.xxx.me
4.commonName_max          = 64
5.commonName              = aaa.xxx.me
5.commonName_max          = 64
6.commonName              = aaa.xxx.me
6.commonName_max          = 64
7.commonName              = aaa.xxx.me
7.commonName_max          = 64
8.commonName              = aaa.xxx.me
8.commonName_max          = 64
9.commonName              = aaa.xxx.com
9.commonName_max          = 64
emailAddress            = admin@tapd.cn
emailAddress_max        = 64

[ root_ca ]
basicConstraints            = critical, CA:true~]# vim tapdLocalExt.cnf 
subjectAltName = @alt_names
extendedKeyUsage = serverAuth

[alt_names]

DNS.1 = *.xxx.xxx.com
DNS.2 = xxx.xxx.com
IP.1 = ingress的ip
IP.2 = lb的ip
#私有CA
 openssl req -x509 -newkey rsa:2048 -out CA.cer -outform PEM -keyout CA.pvk -days 10000 -verbose -config CA.cnf -nodes -sha256 -subj "/CN=aaa CA"#私钥
 openssl req -newkey rsa:2048 -keyout aaa.pvk -out aaa.req -subj "/CN=*.xxx.xxx.com" -sha256 -nodes#公钥
 openssl x509 -req -CA  CA.cer -CAkey CA.pvk -in aaa.req -out aaa.cer -days 10000 -extfile aaaLocalExt.cnf -sha256 -set_serial 0x1113注:该脚本修该的地方就是 enerate_ca.sh你的私钥,tapdCA.cnf应答文件,tapdLocalExt.cnf你要解析的ip地址
三.脚本自动生成通配符ssl证书
新建文件 gencert.sh ,编辑并加入以下内容:

#!/usr/bin/env bash
#
# Copyright 2020 Liu Hongyu (eliuhy@163.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
set -e

DOMAIN="$1"
WORK_DIR="$(mktemp -d)"

if [ -z "$DOMAIN" ]; then
  echo "Domain name needed."
  exit 1
fi

echo "Temporary working dir is $WORK_DIR "
echo "Gernerating cert for $DOMAIN ..."

#
# Fix the following error:
# --------------------------
# Cannot write random bytes:
# 139695180550592:error:24070079:random number generator:RAND_write_file:Cannot open file:../crypto/rand/randfile.c:213:Filename=/home/eliu/.rnd
#
[ -f $HOME/.rnd ] || dd if=/dev/urandom of=$HOME/.rnd bs=256 count=1

openssl genrsa -out $WORK_DIR/ca.key 4096

openssl req -x509 -new -nodes -sha512 -days 3650 \
  -subj "/C=CN/ST=Beijing/L=Beijing/O=example/OU=Personal/CN=$DOMAIN" \
  -key $WORK_DIR/ca.key \
  -out $WORK_DIR/ca.crt

openssl genrsa -out $WORK_DIR/server.key 4096

openssl req -sha512 -new \
  -subj "/C=CN/ST=Beijing/L=Beijing/O=example/OU=Personal/CN=$DOMAIN" \
  -key $WORK_DIR/server.key \
  -out $WORK_DIR/server.csr

cat > $WORK_DIR/v3.ext <<-EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
DNS.1=$DOMAIN
DNS.2=*.$DOMAIN
EOF

openssl x509 -req -sha512 -days 3650 \
  -extfile $WORK_DIR/v3.ext \
  -CA $WORK_DIR/ca.crt -CAkey $WORK_DIR/ca.key -CAcreateserial \
  -in $WORK_DIR/server.csr \
  -out $WORK_DIR/server.crt

openssl x509 -inform PEM -in $WORK_DIR/server.crt -out $WORK_DIR/$DOMAIN.cert

mkdir -p ./$DOMAIN
cp $WORK_DIR/server.key $WORK_DIR/server.crt ./$DOMAIN
假设我们要为 example.com 生成证书,执行如下命令:
./gencert.sh example.com
生成的后的目录结构如下:
.
├── example.com
│   ├── server.crt
│   └── server.key
└── gencert.sh
然后查看通配符ssl
for i in `find . -maxdepth 2 -name "*.crt"`;do openssl x509 -in $i -text -noout;done



四.导出证书

sz server.crt server.key