New-SelfSignedCertificate -DnsName localhost -CertStoreLocation cert:\LocalMachine\My
y default, a self-signed certificate is generated with the following settings:
Cryptographic algorithm: RSA;
Key length: 2048 bit;
Acceptable key usage: Client Authentication and Server Authentication;
The certificate can be used for Digital Signature, Key Encipherment;
Certificate validity period: 1 year.
Using the Get-ChildItem cmdlet, you can display all the parameters of the created certificate by its Thumbprint:
Get-ChildItem -Path "Cert:\LocalMachine\My" | Where-Object Thumbprint -eq 174535541CF0728DAE9FC8FF65401409DF53A03C | Select-Object *
You can create a certificate chain. First, a root certificate (CA) is created, and based on it, an SSL server certificate is generated:
$rootCert = New-SelfSignedCertificate -Subject 'CN=TestRootCA,O=TestRootCA,OU=TestRootCA' -KeyExportPolicy Exportable -KeyUsage CertSign,CRLSign,DigitalSignature -KeyLength 2048 -KeyUsageProperty All -KeyAlgorithm 'RSA' -HashAlgorithm 'SHA256' -Provider 'Microsoft Enhanced RSA and AES Cryptographic Provider'
New-SelfSignedCertificate -CertStoreLocation cert:\LocalMachine\My -DnsName "MyHost" -Signer $rootCert -KeyUsage KeyEncipherment,DigitalSignature
In order to export the generated certificate with a private key to a password-protected PFX file, you need to specify its Thumbprint. It can be copied from the results of the New-SelfSignedCertificate command. You also need to specify the certificate security password and convert it to SecureString format:
$CertPassword = ConvertTo-SecureString -String “YourPassword” -Force –AsPlainText
Export-PfxCertificate -Cert cert:\LocalMachine\My\2779C7928D055B21AAA0Cfe2F6BE1A5C2CA83B30 -FilePath C:\test.pfx -Password $CertPassword
The certificate public key can be exported as follows:
Export-Certificate -Cert Cert:\LocalMachine\My\2779C7928D055B21AAA0Cfe2F6BE1A5C2CA83B30 -FilePath C:\tstcert.cer
you can also generate a wildcard certificate for the entire domain namespace. To do it, specify *.TestHost.com as a server name.
New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname *.TestHost.com
Document Protection Certificate
Data Protection API can encrypt files on your system using a Document Protection Certificate. Using the New-SelfSignedCertificate cmdlet, we can easily make a certificate to encrypt your documents.
$Params = @{
"DnsName" = "MyHost"
"CertStoreLocation" = "Cert:\CurrentUser\My"
"KeyUsage" = "KeyEncipherment","DataEncipherment","KeyAgreement"
"Type" = "DocumentEncryptionCert"
}
PS C:\> New-SelfSignedCertificate @Params