github.com/Venafi/vcert/v5@v5.10.2/pkg/playbook/util/capistore/embedded/retrieve-cert.ps1 (about) 1 <################## 2 .DESCRIPTION 3 retrieve-cert verifies an end-entity certificate is installed in the Personal CAPI store and saves it to a file 4 .PARAMETER friendlyName 5 A text string that is used to identify the certificate when extracting it from the CAPI store 6 .PARAMETER certStore 7 The location to store the certificate in CAPI 8 #> 9 ##################> 10 Set-StrictMode -Version Latest 11 12 function retrieve-cert { 13 [CmdletBinding()] 14 param ( 15 [Parameter(Mandatory)] 16 [string] $friendlyName, 17 [Parameter(Mandatory)] 18 [System.Security.Cryptography.X509Certificates.storeName] $storeName, 19 [Parameter(Mandatory)] 20 [System.Security.Cryptography.X509Certificates.storeLocation] $storeLocation 21 ) 22 # Get the certificate store 23 $store = New-Object System.Security.Cryptography.X509Certificates.X509Store($storeName, $storeLocation) 24 $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly) 25 26 # Find unexpired certificates by friendly name 27 $certs = $store.Certificates | Where-Object { ($_.FriendlyName -eq $friendlyName) -and ($_.NotAfter -gt (Get-Date)) } 28 29 # Close the certificate store 30 $store.Close() 31 32 # If there is more than one cert with this friendly name, get the one expiring furthest in the future 33 $cert = $null 34 if ($null -ne $certs) { 35 $cert = ($certs | Sort-Object -Descending -Property 'NotAfter')[0] 36 } 37 38 # Save the certificate to a file 39 if ($null -ne $cert) { 40 $certBytes = $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert) 41 $base64Cert = [System.Convert]::ToBase64String($certBytes) 42 $certPem = "-----BEGIN CERTIFICATE-----`n" + ($base64Cert -replace "(.{64})", "`$1`n") + "`n-----END CERTIFICATE-----`n" 43 Write-Output -InputObject $certPem 44 } else { 45 Write-Output -InputObject "certificate not found: $($friendlyName)" 46 } 47 }