#!/bin/bash
mkdir ~/Desktop/Microsoft_Certs
# make directory for resulting certs
[[ ! -d ./MS-CAs ]] && mkdir ./MS-CAs && mkdir ./MS-CAs/PEMs && mkdir ./MS-CAs/CERs
# convert the p7b bundle to a concatenated .pem file
openssl pkcs7 -in ~/Downloads/m365_chain_certs_itar20201012.p7b -print_certs -out ./MS-CAs/MS_All-CAs.pem
# split .pem into separate certs
split -p "subject=" ./MS-CAs/MS_All-CAs.pem ./MS-CAs/MS_CA-
# rename each cert file to CN of cert
cd ./MS-CAs
for f in MS_CA-*;do
name=$(openssl x509 -noout -subject -in $f | sed -n '/^subject/s/^.*CN=//p')
mv "$f" ./PEMs/"$name".pem
ditto ./PEMs/"$name".pem ./CERs/"$name".cer
done
# cleanup
rm ./MS_All-CAs.pem
echo "Folder MS-CAs created and certificates extracted."
open ~/Desktop