Public/Get-DSCEncryptionCert.ps1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
<#
.SYNOPSIS This function creates a New Self-Signed Certificate meant to be used for DSC secret encryption and exports it to the specified directory. .DESCRIPTION See .SYNOPSIS .NOTES .PARAMETER MachineName This parameter is MANDATORY. This parameter takes a string that represents the Subject Alternative Name (SAN) on the Self-Signed Certificate. .PARAMETER ExportDirectory This parameter is MANDATORY. This parameter takes a string that represents the full path to a directory that will contain the new Self-Signed Certificate. .EXAMPLE # Import the MiniLab Module and - PS C:\Users\zeroadmin> Get-DSCEncryptionCert -MachineName $env:ComputerName -ExportDirectory "C:\DSCConfigs" #> function Get-DSCEncryptionCert { [CmdletBinding()] param ( [Parameter(Mandatory=$True)] [string]$MachineName, [Parameter(Mandatory=$True)] [string]$ExportDirectory ) if (!$(Test-Path $ExportDirectory)) { Write-Error "The path '$ExportDirectory' was not found! Halting!" $global:FunctionResult = "1" return } $CertificateFriendlyName = "DSC Credential Encryption" $Cert = Get-ChildItem -Path "Cert:\LocalMachine\My" | Where-Object { $_.FriendlyName -eq $CertificateFriendlyName } | Select-Object -First 1 if (!$Cert) { $NewSelfSignedCertExSplatParams = @{ Subject = "CN=$Machinename" EKU = @('1.3.6.1.4.1.311.80.1','1.3.6.1.5.5.7.3.1','1.3.6.1.5.5.7.3.2') KeyUsage = 'DigitalSignature, KeyEncipherment, DataEncipherment' SAN = $MachineName FriendlyName = $CertificateFriendlyName Exportable = $True StoreLocation = 'LocalMachine' StoreName = 'My' KeyLength = 2048 ProviderName = 'Microsoft Enhanced Cryptographic Provider v1.0' AlgorithmName = "RSA" SignatureAlgorithm = "SHA256" } New-SelfsignedCertificateEx @NewSelfSignedCertExSplatParams # There is a slight delay before new cert shows up in Cert: # So wait for it to show. while (!$Cert) { $Cert = Get-ChildItem -Path "Cert:\LocalMachine\My" | Where-Object {$_.FriendlyName -eq $CertificateFriendlyName} } } $null = Export-Certificate -Type CERT -Cert $Cert -FilePath "$ExportDirectory\DSCEncryption.cer" $CertInfo = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new() $CertInfo.Import("$ExportDirectory\DSCEncryption.cer") [pscustomobject]@{ CertFile = Get-Item "$ExportDirectory\DSCEncryption.cer" CertInfo = $CertInfo } } |