create-certificate.sh 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/env bash
  2. # Generates a wildcard certificate for a given domain name.
  3. set -e
  4. if [ -z "$1" ]; then
  5. echo -e "\e[43mMissing domain name!\e[49m"
  6. echo
  7. echo "Usage: $0 example.com"
  8. echo
  9. echo "This will generate a wildcard certificate for the given domain name and its subdomains."
  10. exit
  11. fi
  12. DOMAIN=$1
  13. if [ ! -f "ca.key" ]; then
  14. echo -e "\e[41mCertificate Authority private key does not exist!\e[49m"
  15. echo
  16. echo -e "Please run \e[93mcreate-ca.sh\e[39m first."
  17. exit
  18. fi
  19. # Generate a private key
  20. openssl genrsa -out "$DOMAIN.key" 2048
  21. # Create a certificate signing request
  22. openssl req -new -subj "/C=US/O=Local Development/CN=$DOMAIN" -key "$DOMAIN.key" -out "$DOMAIN.csr"
  23. # Create a config file for the extensions
  24. >"$DOMAIN.ext" cat <<-EOF
  25. authorityKeyIdentifier=keyid,issuer
  26. basicConstraints=CA:FALSE
  27. keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
  28. extendedKeyUsage = serverAuth, clientAuth
  29. subjectAltName = @alt_names
  30. [alt_names]
  31. DNS.1 = $DOMAIN
  32. DNS.2 = *.$DOMAIN
  33. EOF
  34. # Create the signed certificate
  35. openssl x509 -req \
  36. -in "$DOMAIN.csr" \
  37. -extfile "$DOMAIN.ext" \
  38. -CA ca.crt \
  39. -CAkey ca.key \
  40. -CAcreateserial \
  41. -out "$DOMAIN.crt" \
  42. -days 3650 \
  43. -sha256
  44. rm "$DOMAIN.csr"
  45. rm "$DOMAIN.ext"
  46. echo -e "\e[42mSuccess!\e[49m"
  47. echo
  48. echo -e "You can now use \e[93m$DOMAIN.key\e[39m and \e[93m$DOMAIN.crt\e[39m in your web server."
  49. echo -e "Don't forget that \e[1myou must have imported \e[93mca.crt\e[39m in your browser\e[0m to make it accept the certificate."