# Get the hostname to use as the common name (CN) of the server certificate
hostname=`hostname`

# Create password files
echo serverdb > serverdb
echo clientdb > clientdb

# Create the server certificate database
if [ -d server_db ]
then
    rm -r server_db
fi
mkdir server_db
certutil -N -d server_db
echo "*** Enter new password: serverdb ***"
keyutil -N -d server_db

# Create the client certificate database
if [ -d client_db ]
then
    rm -rf client_db
fi
mkdir client_db
certutil -N -d client_db
echo "*** Enter new password: clientdb ***"
keyutil -N -d client_db

# Generate a key pair for the root CA (certificate authority) certificate
keyutil -G -d server_db -w serverdb -f server_db/cert7.db

# Generate a key pair for the server certificate
keyutil -G -d server_db -w serverdb -f server_db/key3.db

# Generate a key pair for the client certificate
keyutil -G -d client_db -w clientdb -f client_db/key3.db

# Display the root CA and server keys
keyutil -L -d server_db -w serverdb

# Read in the root CA key
echo '2nd and 3rd bytes of 1st mod 00:ab:cd => abcd'
read ROOTCA

# Read in the server key
echo '2nd and 3rd bytes of 2nd mod 00:ab:cd => abcd'
read SERVER

# Display the client key
keyutil -L -d client_db -w clientdb

# Read in the client key
echo '2nd and 3rd bytes of mod 00:ab:cd => abcd'
read CLIENT

# Create the root CA certificate (self-signed)
certutil -R -s "CN=root.com,O=MyCo,ST=California,C=US" -k $ROOTCA -o server_db/rootca.req -d server_db -f serverdb
certutil -C -i server_db/rootca.req -o server_db/rootca.crt -k $ROOTCA -x -m 1234 -d server_db -f serverdb
certutil -A -n "My Root CA" -i server_db/rootca.crt -t "CTu,CTu,CTu" -d server_db -f serverdb

# Create the server cerificate (signed by root CA)
certutil -R -s "CN=$hostname,O=MyCo,ST=California,C=US" -k $SERVER -o server_db/server.req -d server_db -f serverdb
certutil -C -c "My Root CA" -i server_db/server.req -o server_db/server.crt -m 1222 -d server_db -f serverdb
certutil -A -n server -i server_db/server.crt -t "u,u,u" -d server_db -f serverdb

# Create the client certificate (signed by root CA)
certutil -R -s "CN=client.com,O=MyCo,ST=California,C=US" -k $CLIENT -o client_db/client.req -d client_db -f clientdb
certutil -C -c "My Root CA" -i client_db/client.req -o client_db/client.crt -m 3434 -d server_db -f serverdb
certutil -A -n client -i client_db/client.crt -t "u,u,u" -d client_db -f clientdb

# Add root CA certificate to client certificate database so the client can authenticate the server
certutil -A -n "My Root CA" -i server_db/rootca.crt -t "CT,CT,CT" -d client_db -f clientdb

# Validate the client and server certificates
certutil -V -u C -n client -d client_db -f clientdb
certutil -V -u V -n server -d server_db -f serverdb
