PowerShell esportazione di un certificato autofirmato su file PEM

Nel post Creazione certificato autofirmato in PowerShell avevo descritto come creare in PowerShell un certificato auto firmato ed esportarlo su file in formato pfx e cer.

Talvolta può essere essere necessario però esportare il certificato su file PEM (Privacy Enhanced Mail) ovvero un file di testo che può contenere contengono uno o più elementi nella codifica ASCII Base64. Il formato PEM, formalizzato dell’IETF (Internet Engineering Task Force) nella RFC 7468, è il più comune per i certificati X.509 e viene utilizzato per archiviare i certificati SSL e le chiavi private associate.

Alcuni software potrebbero utilizzare i file pem per gestire funzionalità di crifratura, un esempio è E-MailRelay un semplice store-and-forward SMTP server che per implementare la cifratura TLS o la STARTTLS utilizza un file PEM contenente la chiave pubblica e privata, a riguardo si veda E-MailRelay – TLS encryption:

“The –server-tls option requires that the –server-tls-certificate option is used to specify a PEM-format file containing a X.509 certificate and private key.”

Di seguito uno script PowerShell di esempio per generare un file PEM contenente la chiave privata e la chiave pubblica di un certificato auto firmato con algoritimo RSA creato tramite il cmdlet New-SelfSignedCertificate. Lo script crea un certificato autofirmato nello store dei certificati dell’utente, lo esporta su file formato pem e quindi lo rimuove dallo store dei certificati.

# Variabili di utilità
$timeStamp = Get-Date -format “yyyy-MM-dd-HH-mm-ss”

# Impostazioni di configurazione
$certFriendlyName = “Certificato Self-Signed per DevAdmin [$timeStamp]”
$certSubject = “C=IT, ST=Cuneo, L=Cuneo, O=DevAdmin, OU=Servizi IT, CN=srvtest01.devadmin.it”
$certExportPath = Join-Path -Path $PSScriptRoot -ChildPath “Certs”
$certExportFileName = “srvtest01.pem”
$certDurationMonths = 120
$certKeyLength = 2048
$certKeyAlgorithm = “RSA”
$certKeySpec = “Signature”
$certKeyUsage = “CertSign”
$certHashAlgorithm = “SHA256”
$certProvider = “Microsoft Enhanced RSA and AES Cryptographic Provider”

# Creazione Certificato autofirmato
$cert=New-SelfSignedCertificate -FriendlyName $certFriendlyName -Subject $certSubject `
-CertStoreLocation Cert:\CurrentUser\My `
-NotAfter (Get-Date).AddMonths($certDurationMonths) `
-KeyAlgorithm $certKeyAlgorithm -KeyLength $certKeyLength -HashAlgorithm $certHashAlgorithm `
-KeySpec $certKeySpec -KeyUsage $certKeyUsage `
-KeyExportPolicy Exportable `
-Provider $certProvider

# Conversione della Public Key in Base64
$certPublicKeyBase64 = [System.Convert]::ToBase64String($cert.RawData, [System.Base64FormattingOptions]::InsertLineBreaks)

# Conversione della Private Key in Base64
$certRSAPrivateKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert)
$certPrivateKeyBytes = $certRSAPrivateKey.Key.Export([System.Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob)
$certPrivateKeyBase64 = [System.Convert]::ToBase64String($certPrivateKeyBytes, [System.Base64FormattingOptions]::InsertLineBreaks)

# Creazione directory per esportazione certificati
New-Item -Path $certExportPath -ItemType Directory -Force

# Export Certificato e della Chiave Privata su file PEM
$certPEMFilePath = Join-Path -Path $certExportPath -ChildPath ($certExportFileName + “.pem”)

$certPEMFileContent = “—–BEGIN PRIVATE KEY—–“
$certPEMFileContent += “`n”
$certPEMFileContent += $certPrivateKeyBase64
$certPEMFileContent += “`n”
$certPEMFileContent += “—–END PRIVATE KEY—–“
$certPEMFileContent += “`n”
$certPEMFileContent += “—–BEGIN CERTIFICATE—–“
$certPEMFileContent += “`n”
$certPEMFileContent += $certPublicKeyBase64
$certPEMFileContent += “`n”
$certPEMFileContent += ‘—–END CERTIFICATE—–‘
$certPEMFileContent += “`n”

$certPEMFileContent| Out-File -FilePath $certPEMFilePath -Encoding Ascii

# Rimozione del certificato dallo store dei cetificati
Remove-Item -Path Cert:\CurrentUser\My\$cert.Thumbprint

Lo script è disponibile sul mio repository GitHub al seguente link https://github.com/ermannog/PowerShell/tree/master/Create-SelfSignedCertificatePEMFile.