 #!/bin/bash
#
# Alter the password used to protect the private key of a certificate exported by MMC into a .pfx file
# When prompted please supply:
# 1. Import Password
#    This is the password you specified to MMC when you exportedpublic.private key combination as .pfx
# 2. Export password
#    The new password to protect the private key. Note it you enter return at the prompt then the .pfx
#    will no longer be password protected.
#    The Tachyon Agent expects a Tachyon.pfx that is NOT password protected.
if [ $# -ne 2 -o -z "$1" -o -z "$2" ] ; then
    echo "Usage: $0 <Original.pfx file> <Converted.pfx file>"
    echo "Actual parameters supplied:" "$@"
    exit 1
fi
echo "Script to alter or remove password protection on the private key within a .pfx file"
echo ""
echo "When prompted for the Import Password please supply the current password of the .pfx file"
echo "When prompted for the Export Password please supply the new password for the .pfx file"
echo "Or simply enter return in order to produce an unprotected .pfx file"
echo ""
PfxFile="$1"
NewPfxFile="$2"
# We could have something like Tachyon.1e.local.pfx in which case we only want to remove the last . field
BaseName=$(basename "$PfxFile" .pfx)
CertFile="/tmp/$BaseName.cer"
KeyFile="/tmp/$BaseName.key"
CaCertFile="/tmp/$BaseName.cacert"
PemFile="/tmp/$BaseName.pem"
echo "1. Extract the public certificate from $PfxFile -> $CertFile"
openssl pkcs12 -clcerts -nokeys -in $PfxFile -out $CertFile
echo "2. Extract the private key from $PfxFile -> $KeyFile"
openssl pkcs12 -nocerts -in $PfxFile -out $KeyFile -nodes
echo "3. Extract the Certificate Authority certificate from $PfxFile -> $CaCertFile"
openssl pkcs12 -cacerts -nokeys -in $PfxFile -out $CaCertFile
# Merge together into a .pem file and then create a new .pfx file..
cat $KeyFile $CertFile $CaCertFile > $PemFile
echo "4. Create a new .pfx file -> $NewPfxFile"
openssl pkcs12 -export -nodes -CAfile $CaCertFile -in $PemFile -out $NewPfxFile
# Tidy up any temp files.
echo "A new .pfx file, with your password choice for the private key, has been written to $NewPfxFile"
rm $CertFile $KeyFile $CaCertFile $PemFile
exit 0