Generate Self-signed certificate with Root CA Signer

Viewed 19014

Scenario: I am using PowerShell on Windows Server 2012r2 to generate a Root certificate and want to use that to sign a newly created Intermediate and Web certificate in dynamic generated (and destroyed) dev/test environments. The scripts are deployed remotely, and the intent is to keep it pure PowerShell if possible. In Windows 10/2016 this is relatively easy, after generating the Root certificate:

$Cert = New-SelfSignedCertificate -Signer $Root -Subject "CN=$Subject"

I've generated the Root certificate using COM X509Enrollment.CX509CertificateRequestCertificate and Security.Cryptography.X509Certificates.X509Certificate2 in a bastardized PS that I've had for some time, mainly because I needed to ensure that the Subject and Usage were set very specifically. I am not quite certain how to use this to sign the standard certificate without the above (which I have used before).

There are some examples using Bouncy Castle (see below) in C# that I could tie into PowerShell, but then I would need to deploy this additionally on the dynamic dev/test environments and I want to be able to do this in Powershell (via COM if needed) with the least dependencies.

4 Answers

How about simply doing this:

$cert = New-SelfSignedCertificate -FriendlyName "MyCA"
      -KeyExportPolicy ExportableEncrypted 
      -Provider "Microsoft Strong Cryptographic Provider" 
      -Subject "SN=TestRootCA" -NotAfter (Get-Date).AddYears($ExpiryInYears) 
      -CertStoreLocation Cert:\LocalMachine\My -KeyUsageProperty All 
      -KeyUsage CertSign, CRLSign, DigitalSignature

Important parameters are -KeyUsageProperty and -KeyUsage.

The easy way of creating a root certificate would be to do the following. Please note the text extension which makes sure that the certificate is a root certificate. Such a certificate must be placed in a root certificate store to indicate trust. E.g. The 'cert:\LocalMachine\My' store.

Make sure that the KeyUsage is what you want. This can of course be changed, but Microsoft is not that good at documenting why you should do what they suggest.

The moving/copying of the certificate must be done done by exporting the certificate and importing it again. Or create the certificate in the correct place. Note that in general, the certificate will only be created in a My store. Some support commands are described in Certificate Provider PowerShell functions.

The certificate will be exportable by default.

$rootCert = New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\My `
            -DnsName "RootCA" `
            -TextExtension @("2.5.29.19={text}CA=true") `
            -KeyUsage CertSign,CrlSign,DigitalSignature;

The code was lifted from https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-create-temporary-certificates-for-use-during-development

Related