How to generate self signed certificate on windows? , Ranjan.info

Most Windows administrators who are familiar with PKI are aware of MakeCert.exeTool, which allows to create self-signed certificates. This tool is part of the Microsoft .NET Framework SDK and the Microsoft Windows SDK. On modern Windows versions (Windows 11/10/8.1 and Windows Server 2022/2019/2016/2012R2) you can generate a self-signed certificate using the built-in PowerShell cmdlet. New-SelfSignedCertificate without using additional tools.

New-SelfSignedCertificate: Creating a Self-Signed Certificate with PowerShell

To generate a self-signed certificate with PowerShell, you can use the built-in new-self-signed certificate cmdlet, which is a part of PowerShell pki (Public Key Infrastructure) Module:

To list all available cmdlets in the PKI module, run the command:

Get-Command -Module PKI

Powershell PKI Module - Manage Certificates on Windows

Self-signed certificates for test/development work for internal intranet services (IIS, Exchange, Web Application Proxies, LDAPS, ADRMS, DirectAccess, etc.) if you cannot deploy or purchase PKI/CA infrastructure It is recommended to use or provide a certificate. A trusted certificate from an external provider.

To generate the certificate, you must specify the values ​​of -dnsname (a server name, the name can be arbitrary and can even be different from the current hostname) and -CertStoreLocation (A local certificate store in which the generated certificate will be placed).

To generate a new SSL certificate (with the default SSLServerAuthentication type) for the DNS name test.contoso.com (use a FQDN name) and place it in Personal Certificates on the computer, run the following command:

New-SelfSignedCertificate -DnsName test.contoso.com -CertStoreLocation cert:\LocalMachine\My

New-Selfsigned Certificate PowerShell Cmdlet on Windows

The command will return the thumbprint, subject, and EnhancedKeyUsageList of the new certificate. By default, such a certificate can be used for client authentication (1.3.6.1.5.5.7.3.2) or server authentication (1.3.6.1.5.5.7.3.1).

If you run this command in a non-elevated PowerShell prompt (without local administrator permissions), an error will appear:

New-SelfSignedCertificate : CertEnroll::CX509Enrollment::_CreateRequest: Access denied. 0x80090010 (-2146893808 NTE_PERM)

If you have specified a non-standard Cryptographic Provider (CSP) (for example, -KeyAlgorithm "ECDSA_secP256r1" -Provider "Microsoft Smart Card Key Storage Provider"parameter), make sure it is installed on your computer (the default is Microsoft Advanced Cryptographic Provider). Otherwise, an error will appear:

New-SelfSignedCertificate: CertEnroll::CX509Enrollment::_CreateRequest: Provider type not defined. 0x80090017 (-2146893801 NTE_PROV_TYPE_NOT_DEF).

By default, a self-signed certificate is generated with the following settings:

  • Cryptographic Algorithm: RSA,
  • Main Length: 2048 bit,
  • Acceptable key usage: client authentication And server authentication,
  • The certificate can be used for: digital signature, key encryption,
  • Certificate Validity Period: 1 year,
  • Crypto Provider: Microsoft Software Key Storage Provider.

This command creates a new certificate and imports it into the computer’s personal certificate store. open certlm.msc MMC snap-in and make sure a new certificate appears in it Personal Section of the computer’s certificate store.

certlm.msc personal certificate storage

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 2175A76B10F843676951965F52A718F635FFA043 | Select-Object *

List Self-Signed Certificate Attributes with PowerShell

PSPath                   : Microsoft.PowerShell.Security\Certificate::LocalMachine\My\2175A76B10F843676951965F52A718F635FFA043
PSParentPath             : Microsoft.PowerShell.Security\Certificate::LocalMachine\My
PSChildName              : 2175A76B10F843676951965F52A718F635FFA043
PSDrive                  : Cert
PSProvider               : Microsoft.PowerShell.Security\Certificate
PSIsContainer            : False
EnhancedKeyUsageList     : {Client Authentication (1.3.6.1.5.5.7.3.2), Server Authentication (1.3.6.1.5.5.7.3.1)}
DnsNameList              : {test.contoso.com}
SendAsTrustedIssuer      : False
EnrollmentPolicyEndPoint : Microsoft.CertificateServices.Commands.EnrollmentEndPointProperty
EnrollmentServerEndPoint : Microsoft.CertificateServices.Commands.EnrollmentEndPointProperty
PolicyId                 :
Archived                 : False
Extensions               : {System.Security.Cryptography.Oid, System.Security.Cryptography.Oid,
System.Security.Cryptography.Oid, System.Security.Cryptography.Oid}
FriendlyName             :
IssuerName               : System.Security.Cryptography.X509Certificates.X500DistinguishedName
NotAfter                 : 12/4/2023 5:35:15 PM
NotBefore                : 12/4/2022 5:15:15 PM
HasPrivateKey            : True
PrivateKey               :
PublicKey                : System.Security.Cryptography.X509Certificates.PublicKey
RawData                  : {48, 130, 3, 45...}
SerialNumber             : 6797F5E3F870478D4D3798BEB291DBF3
SubjectName              : System.Security.Cryptography.X509Certificates.X500DistinguishedName
SignatureAlgorithm       : System.Security.Cryptography.Oid
Thumbprint               : 2175A76B10F843676951965F52A718F635FFA043
Version                  : 3
Handle                   : 2834444631568
Issuer                   : CN=test.contoso.com
Subject                  : CN=test.contoso.com
Comment, This self-signed certificate will expire 1 year after it is generated. You can set a different certificate validity period by using -not later alternative. For example, you can issue an SSL/TLS certificate with a validity period of three years with the following command:

$todaydt = Get-Date
$3years = $todaydt.AddYears(3)
New-SelfSignedCertificate -dnsname test.contoso.com -notafter $3years -CertStoreLocation cert:\LocalMachine\My

You can create a certificate chain. First, a root certificate (CA) is created. Then based on this, 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 "test2.contoso.com" -Signer $rootCert -KeyUsage KeyEncipherment,DigitalSignature

To change the certificate key length and encryption algorithm, you need to use -KeyAlgorithm, -KeyLengthAnd -HashAlgorithm alternative. For example:

New-SelfSignedCertificate -KeyAlgorithm RSA -KeyLength 2048 -HashAlgorithm "SHA256" …

Microsoft Platform Crypto Provider Allows you to use the device’s Trusted Platform Module chip (TPM 2.0) to protect the key.

New-SelfSignedCertificate -Type Custom -Provider "Microsoft Platform Crypto Provider" ...

You can create a document encryption certificate to protect your documents and email. Use DocumentEncryptionCert When creating the certificate, type:

$Params = @{
"DnsName" = "myhostname"
"CertStoreLocation" = "Cert:\\CurrentUser\\My"
"KeyUsage" = "KeyEncipherment","DataEncipherment","KeyAgreement"
"Type" = "DocumentEncryptionCert"
}
$doccert=New-SelfSignedCertificate @Params

Check the CertificateEnhancedCuseList value:

$doccert|select EnhancedKeyUsageList

{Document Encryption (1.3.6.1.4.1.311.80.1)}

Get Certificate Enhanced Key Usage List: Document Encryption Certificate

Create a certificate with a Subject Alternative Name (SAN) using PowerShell

The New-SelfSignedCertificate cmdlet allows you to create multiple individual certificates subject alternate name ,Sans).

Comment, Makecert.exeThe tool cannot create SAN and wildcard certificates, unlike the New-SelfSignedCertificate cmdlet.[/alert]

If you want to create a certificate with more than one name, the first name in the DnsName parameter will be used as the CN (Common Name) of the certificate. For example, create a self-signed SAN certificate with the following names:

  • Subject Name (CN): adfs1.contoso.com
  • Subject Alternative Names (DNS): web_gw.contoso.com
  • Subject Alternative Names (DNS): enterprise_reg.contoso.com

You can run the following command to generate certificates with different common names (or even for multiple domains):

New-SelfSignedCertificate -DnsName adfs1.contoso.com,web_gw.contoso.com,enterprise_reg.contoso.com -CertStoreLocation cert:\LocalMachine\My

Certificate with multiple subject alternate names

Additionally, you can generate a wildcard Certificate for the entire domain namespace by specifying *.contoso.com as server name.

New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname *.contoso.com

You can create self-signed certificates not only for DNS hostnames, but also for IP addresses. To do this, you need to use -TextExtension instead of the -DnsName parameter. For example:

New-SelfSignedCertificate -TextExtension @("2.5.29.17={text}IPAddress=10.1.2.3&DNS=TESTServer1&DNS=TESTServer1.local")

As you can see, the Subject Alternative Name field now contains the host’s IP address and its DNS name.

Create Self-Signed Certificate for IP Address on Windows

How to export self signed certificate on Windows?

To export a certificate generated with a private key to a password-protected PFX file, you need to specify its thumbprint. This can be copied from the results of the New-SelfSignedCertificate command. You also need to specify the certificate’s 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

Export-PfxCertificate

You can export the certificate public key as follows (the private key is not included in the export):

Export-Certificate -Cert Cert:\LocalMachine\My\2779C7928D055B21AAA0Cfe2F6BE1A5C2CA83B30 -FilePath C:\tstcert.cer

Make sure that the *.CER (PFX) certificate file appears in the specified directory. If you right-click it and “select”install certificatemenu item, you can access Certificate Import Wizard To add the certificate to Trusted Root Certificates on your computer.

install certificate with file explorer on windows 10

Select certificate store location -> local machineKeep all the certificates in the following store -> trusted root certification authority,

Install certificates to trusted root certification authorities

[alert]You can generate a certificate and immediately import it into the computer’s trusted root certificate store using the command:

$SelfSignCert=New-SelfSignedCertificate …..
$certFile = Export-Certificate -Cert $SelfSignCert -FilePath C:\ps\export-certname.cer
Import-Certificate -CertStoreLocation Cert:\LocalMachine\AuthRoot -FilePath $certFile.FullName

You can manually deploy this public key or certificate file to all user computers and servers in an Active Directory domain by using a GPO (How to deploy certificates for users with a GPO?).

Creating a Self-Signed Certificate for Code Signing on Windows

In PowerShell 3.0, the New-SelfSifgnedCertificate cmdlet only generates an SSL certificate that cannot be used for driver code signing, applications, or scripts (as opposed to the certificate generated by the makecert utility).

You can use the New-SelfSifgnedCertificate cmdlet to issue code signing Certification in PowerShell version 5.0 and newer.

To generate a self-signed certificate to code sign an application, run the command:

$cert = New-SelfSignedCertificate -Subject "My Code Signing Certificate” -Type CodeSigningCert -CertStoreLocation cert:\LocalMachine\My

Now you can sign your PowerShell script file with a self-signed certificate:

Set-AuthenticodeSignature -FilePath C:\PS\my_posh_script.ps1 -Certificate $cert

if you are getting a unknown error Warning when executing the command, it means that the certificate is not trusted, because it is located in the user’s personal certificate store.

Signing PowerShell script using self-signed certificate - unknown error

You need to move it to the trusted root certificate store (don’t forget to periodically scan the Windows certificate root store for untrusted and suspicious certificates and update the list of trusted root certificates).

Move-Item -Path $cert.PSPath -Destination "Cert:\CurrentUser\Root"

You can now use this self-signed certificate to sign your PowerShell scripts, drivers, or applications.

Creating SHA-256 Self-Signed SSL Certificate in IIS on Windows Server

Please note that when creating a self-signed certificate for IIS through the Internet Information Manager console ( generate self signed certificate Actions menu item), an SSL certificate is created using the SHA-1 encryption algorithm. Such certificates are considered untrusted by many browsers and cannot be used to establish a secure connection (or you may see other SSL warnings and errors). The New-SelfSignedCertificate cmdlet allows you to create a more popular type of certificate using the SHA-256 encryption algorithm.

IIS creates self signed SSL certificate on windows server

You can bind a self-signed SHA-256 certificate generated from PowerShell to an IIS site on Windows Server. If you have created an SSL certificate using PowerShell and placed it in the computer’s certificate store, it will automatically become available to IIS sites.

Self-Signed SHA256 Certificate Binding for IIS Site on Windows Server

Open the IIS Manager console (inetmgr.exe), select your site, and then select the certificate you created site binding alternative. Save your changes.

You can also bind an SSL certificate to an IIS site by its thumbprint:

New-IISSiteBinding -Name "Default Web Site" -BindingInformation "*:443:" -CertificateThumbPrint $yourCert.Thumbprint -CertStoreLocation "Cert:\LocalMachine\My" -Protocol https

Leave a Comment