openssl 生成CA并且使用CA签发证书

./cert-tool.sh ca 365

./cert-tool.sh server 365

#!/bin/bash
mkdir -p cert
if [ -n "$2" ]; then
  day=$2
else
  day=10000
fi

clear_old(){
  rm -f cert/*        
}


read -p "rm cert/* [Y/n]" input
case $input in
  Y)
   clear_old
  ;;
  y)
   clear_old
  ;;
esac

cd cert

ca(){
cat > openssl.cnf <<EOF
[ req ]
distinguished_name = req_distinguished_name
x509_extensions = v3_ca

[ req_distinguished_name ]
countryName                     = Country Name (2 letter code)
countryName_default             = CN
organizationalUnitName          = Organizational Unit Name (eg, section)
organizationalUnitName_default  = admin
commonName                      = Common Name (eg, your name or your server\'s hostname)
commonName_max                  = 64
commonName_default              = Private Root CA

[ v3_ca ]
basicConstraints = CA:true
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
keyUsage = cRLSign, keyCertSign
EOF

  openssl genrsa -out ca.key 2048
  openssl req -new -sha256 -out ca.csr -key ca.key -config openssl.cnf
  openssl x509 -req -in ca.csr -out ca.crt -signkey ca.key -days $day -extensions v3_ca -extfile openssl.cnf 
  openssl x509 -in ca.crt -noout -text
  cp -f ca.crt ../
  cp -f ca.key ../
}

server(){
cat > openssl.cnf <<EOF
[ req ]
distinguished_name = req_distinguished_name
x509_extensions = basic_exts

[ req_distinguished_name ]
countryName                     = Country Name (2 letter code)
countryName_default             = CN
organizationalUnitName          = Organizational Unit Name (eg, section)
organizationalUnitName_default  = admin
commonName                      = Common Name (eg, your name or your server\'s hostname)
commonName_max                  = 64
commonName_default              = example.com

[ basic_exts ]
basicConstraints = CA:false
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer:always
#subjectAltName = @alt_names

[alt_names]
DNS.1 = *.example.com
EOF

  openssl genrsa -out server.key 2048
  openssl req -new -sha256 -out server.csr -key server.key -config openssl.cnf
  openssl x509 -req -in server.csr -CA ../ca.crt -CAkey ../ca.key -CAcreateserial -out server.crt -days $day -extensions basic_exts -extfile openssl.cnf
  openssl x509 -in server.crt -noout -text
}

case $1 in
  ca) ca
  ;;
  server) server
  ;;
  *)
    echo "$0 ca|server"
  ;; 
esac

 

posted @ 2021-07-19 12:03  三木燕  阅读(157)  评论(0编辑  收藏  举报