Skip to content

Instantly share code, notes, and snippets.

@mkdym
Last active December 5, 2017 08:37
Show Gist options
  • Save mkdym/95b9eb27ae5864c3967d9b08e7f4ab4f to your computer and use it in GitHub Desktop.
Save mkdym/95b9eb27ae5864c3967d9b08e7f4ab4f to your computer and use it in GitHub Desktop.
generate https cert
#!/bin/sh
#
# generate ssl cert for https
#
set -e
if [ "$DEBUG"x = "true"x ]; then
set -x
fi
#cd `dirname $0`
SUBJ_C=${SUBJ_C:-CN}
SUBJ_ST=${SUBJ_ST:-myprovince}
SUBJ_L=${SUBJ_L:-mycity}
SUBJ_O=${SUBJ_O:-myorganization}
SUBJ_OU=${SUBJ_OU:-mygroup}
subj_prefix="/C=$SUBJ_C/ST=$SUBJ_ST/L=$SUBJ_L/O=$SUBJ_O/OU=$SUBJ_OU"
usage(){
echo "usage: `basename $0` domain [rootcn]"
}
domain=$1
rootcn=$2
if [ -z "$domain" ]; then
usage
exit 1
fi
if [ -z "$rootcn" ]; then
rootcn=rootca
fi
subj_root="$subj_prefix/CN=$rootcn"
subj_server="$subj_prefix/CN=$domain"
cert_dir=./$rootcn
mkdir -p $cert_dir
if [ ! -f "$cert_dir/$rootcn.cer" ] || [ ! -f "$cert_dir/$rootcn.pem" ]; then
echo "!!!!!generate root ca cert..."
# generate private key for ca cert
openssl genrsa -aes256 -passout pass:test -out $cert_dir/$rootcn-key.pem 1024
# remove passwd from private key for ca
openssl rsa -in $cert_dir/$rootcn-key.pem -passin pass:test -out $cert_dir/$rootcn.pem
# generate ca cert request
openssl req -new -key $cert_dir/$rootcn.pem -out $cert_dir/$rootcn.csr -subj "$subj_root"
# sign ca cert request by openssl
openssl x509 -req -days 365 -sha256 -extensions v3_ca -signkey $cert_dir/$rootcn.pem -in $cert_dir/$rootcn.csr -out $cert_dir/$rootcn.cer
else
echo "!!!!!found root ca cert"
fi
# write ext file for server cert
cat > $cert_dir/$domain.ext << EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = $domain
EOF
# generate private key for server cert
openssl genrsa -aes256 -passout pass:test -out $cert_dir/$domain-key.pem 1024
# remove passwd from private key for server
openssl rsa -in $cert_dir/$domain-key.pem -passin pass:test -out $cert_dir/$domain.key
# generate server cert request
openssl req -new -key $cert_dir/$domain.key -out $cert_dir/$domain.csr -subj "$subj_server"
# sign server cert request by ca cert
openssl x509 -req -days 365 -sha256 -extfile $cert_dir/$domain.ext -CA $cert_dir/$rootcn.cer -CAkey $cert_dir/$rootcn.pem -CAserial $cert_dir/$rootcn.srl -CAcreateserial -in $cert_dir/$domain.csr -out $cert_dir/$domain.cer
echo "!!!!!success"
echo "!!!!!just need three files: $cert_dir/$rootcn.cer, $cert_dir/$domain.key, $cert_dir/$domain.cer"
echo "!!!!!install $rootcn.cer into trusted root certificate authority on Windows, and then use $domain.key and $domain.cer in your https site, ie and chrome will trust the cert"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment