skip to content

mkcert: Local CA Installation and cert generation

/ 2 min read

ⓘ Ensure 'mkcert' is installed on your Linux system. Follow the official guide for installation instructions.
# Script takes two option, --install and another option --uninstall
# Then runs two functions, install and uninstall

install() {
    # Check if mkcert is installed
    if ! command -v mkcert &> /dev/null; then
        echo "mkcert is not installed"
        return 1
    fi

    # Create a certificate for localhost
    mkcert localhost

    # Create a new directory for the certificates
    mkdir -p generated_certs

    # Move the certificate to generated_certs
    mv localhost.pem generated_certs

    # Move the key to generated_certs
    mv localhost-key.pem generated_certs

    echo "mkcert is installed and certificates are generated."
    return 0
}


uninstall() {
    # Check if mkcert is installed
    if command -v mkcert &> /dev/null
    then
        # Uninstall rootCA
        mkcert -uninstall
        # Remove rootCA from home directory
        rm -f "$(mkcert -CAROOT)"
    else
        echo "mkcert is not installed"
        # Return 1
        return 1
    fi
}



# Check if the user has root privileges
if [ "$EUID" -ne 0 ]
then
    # If not, print error message
    echo "Please run as root"
    # Exit with error code 1
    exit 1
fi

# Check if the user has provided an option
if [ -z "$1" ]
then
    # If not, print error message with usage
    echo "Usage: $0 --install | --uninstall"
    # Exit with error code 1
    exit 1
fi


# Check for command-line options
while [[ "$#" -gt 0 ]]; do
    case "$1" in
        --install)  # If the --install option is provided, call the install function
            install
            ;;
        --uninstall)  # If the --uninstall option is provided, call the uninstall function
            uninstall
            ;;
        *)  # Handle other options or arguments as needed
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
    shift
done