How to import self-signed certificate to macOS system keychain

I described a simple way to generate self-signed SSL certificate using command-line two weeks ago. So, today I will share very useful trick for MacOS users which is a shell script to import self-signed certificate to macOS system keychain using command-line.

Shell script.

# MacOS system keychain - import website certificate

# temporary file to store certificate

# delete temporary file on exit
trap "unlink $certificate_file" EXIT

# domain address (eg.

# execute only if domain is provided
if [ ! -z "$certificate_domain" ]; then
  echo "domain address: $certificate_domain"

  # download remote certificate
  echo -n | openssl s_client -connect ${certificate_domain}:443 2>/dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > $certificate_file

  # get certificate size and status
  certificate_size=$(stat -f "%z" $certificate_file)
  certificate_status=$(openssl x509 -in $certificate_file -noout 2>/dev/null; echo $?)

  if [ "$certificate_size" -gt "0" ] && [ "$certificate_status" -eq "0" ]; then
    echo "certificate details: "
    openssl x509 -in $certificate_file -noout -text | awk "/X509v3 Subject Alternative Name/{getline;print}; /Subject:/ {print}" | tr -s "^ "

    # import certificate to system keychain
    sudo security add-trusted-cert -d -r trustRoot -k "/Library/Keychains/System.keychain" $certificate_file
    if [ "$?" -eq "0" ]; then
      echo "certificate imported"
      echo "certificate not imported"
      exit 2
    echo "certificate not downloaded or bogus"
    exit 1

Sample usage.

$ bash
domain address:
certificate details:
 Subject: OU=Domain Control Validated, OU=PositiveSSL Multi-Domain,,,,,
certificate imported
Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland