How to create an interactive Bash script to generate self-signed SSL certificates

How to create an interactive Bash script to generate self-signed SSL certificates

In this article, we will create an interactive Bash script to generate self-signed SSL certificates using OpenSSL, a widely used tool for encryption and certificate management.

Self-signed SSL certificates are useful for testing HTTPS connections or for internal use in development environments. In this article, we will create an interactive Bash script to generate self-signed SSL certificates using OpenSSL, a widely used tool for encryption and certificate management.

We will create a Bash script called generate_ssl.sh that will prompt the user for certificate details, such as the domain name, certificate lifetime, and output path. The script will then create a private key and a self-signed certificate using OpenSSL.


#!/bin/bash

read -p "Enter domain name (example: example.com): " domain
read -p "Enter number of days the certificate is valid: " days
read -p "Enter output path (directory to save certificate and key): " output_dir

# Check if output directory exists, otherwise create it
if [ ! -d "$output_dir" ]; then
  mkdir -p "$output_dir"
fi

# File names for key and certificate
key_file="$output_dir/$domain.key"
cert_file="$output_dir/$domain.crt"

# Generate private key
openssl genpkey -algorithm RSA -out "$key_file" -aes256
if [ $? -ne 0 ]; then
  echo "Error generating private key."
  exit 1
fi

# Generate self-signed certificate
openssl req -new -x509 -key "$key_file" -out "$cert_file" -days "$days" -subj "/CN=$domain"
if [ $? -ne 0 ]; then
  echo "Error generating SSL certificate."
  exit 1
fi

echo "SSL certificate generated successfully!"
echo "Private key: $key_file"
echo "Certificate: $cert_file"

The script can be further enhanced to include additional features, such as:

  • OpenSSL presence check: Before running commands, the script can check if OpenSSL is installed.
  • Improved error handling: Provide more detailed error messages if something goes wrong.
  • Support for advanced configurations: For example, generate a custom OpenSSL configuration file with more certificate options.

Conclusion

Creating a self-signed SSL certificate with an interactive Bash script is a great way to automate certificate setup for development and testing environments. While these certificates are not suitable for production use, they are useful for testing purposes or internal use.

This script is a good starting point and can be customized to your specific needs, such as including additional configuration options or integrating with other automation tools.