ยง2023-08-02

To add the Subject Alternative Name (SAN) extension to your X.509 certificate, you need to create a configuration file for OpenSSL that includes the SAN extension settings. Below are the steps to modify your script to include the SAN extension:

Create a configuration file (e.g., openssl.cnf) with the following content:

To add the Subject Alternative Name (SAN) extension to your X.509 certificate, you need to create a configuration file for OpenSSL that includes the SAN extension settings. Below are the steps to modify your script to include the SAN extension:

Create a configuration file (e.g., openssl.cnf) with the following content:

[req]
req_extensions = v3_req

[v3_req]
subjectAltName = @alt_names

[alt_names]
DNS.1 = your.hostname.com
DNS.2 = additional.hostname.com

Add more DNS entries as needed for additional domain names or IP addresses.

Replace your.hostname.com with the primary domain name (Common Name - CN) and add additional DNS.x entries for each Subject Alternative Name (SAN) you want to include in the certificate.

Modify your script to use the configuration file while generating the certificate:

#!/bin/bash

if [ "$1" = "" ]; then
  echo 'hostname is fully qualified name, i.e. orgPi5Arch.yushei.net'
  echo 'Please enter your hostname (CN):'
  exit 1
fi

HOST_NAME="$1"
SUBJECT="/C=Tw/ST=Taiwan/L=Taichung/O=yushei.net/OU=ComputerDepartment/CN=$HOST_NAME"

# Generate the CSR with the SAN extension
openssl req -new -nodes -newkey rsa:4096 -subj "$SUBJECT" -keyout "$HOST_NAME.key" -out "$HOST_NAME.csr" -config openssl.cnf

# Sign the certificate with the SAN extension
openssl x509 -CA mongoCA.crt -CAkey mongoCA.key -CAcreateserial -req -days 395 -in "$HOST_NAME.csr" -out "$HOST_NAME.crt" -extensions v3_req -extfile openssl.cnf

# Concatenate the key and certificate into a PEM file
cat "$HOST_NAME.key" "$HOST_NAME.crt" > "$HOST_NAME.pem"

# Clean up temporary files
rm "$HOST_NAME.key" "$HOST_NAME.crt" "$HOST_NAME.csr"

Remember to adjust the path to your mongoCA.crt and mongoCA.key files accordingly.

With these modifications, your X.509 certificate will include the Subject Alternative Name (SAN) extension, allowing it to be used with multiple domain names or IP addresses.