#!/bin/bash
set -e

if [ "$#" -ne 1 ]; then
    echo "Como usar: $0 arquivo.pfx" >&2
    exit 1;
fi

if [ ! -e "$1" ]; then
    echo "Arquivo nao encontrado: $1" >&2
    exit 1;
fi

filename=$(basename "$1")
extension="${filename##*.}"
filename="${filename%.*}"

echo -n "Insira a senha do certificado: "
read -s pfxpass

echo

#extract private key
openssl pkcs12 -in "$1" -nocerts -out keyfile-encrypted.key -passin pass:$pfxpass -passout pass:1234 > /dev/null

#decrypt private key
openssl rsa -in keyfile-encrypted.key -out "$filename.key" -passin pass:1234 > /dev/null

#delete encrypted private key
rm keyfile-encrypted.key

#extract certificate
openssl pkcs12 -in "$1" -clcerts -nokeys -out "$filename.crt" -passin pass:$pfxpass > /dev/null

echo "Extracao finalizada!"
echo "Arquivos gerados: $filename.crt e $filename.key"