Comments on this page are supposed to improve article content and no technical support is provided. For technical questions, please visit project home page at: GitHub

New-SelfSignedCertificateEx

Synopsis

This cmdlet generates a self-signed or CA-signed certificate

Syntax

New-SelfSignedCertificateEx [-Subject] <String> [[-NotBefore] <DateTime>] [[-NotAfter] <DateTime>] [-SerialNumber <String>] [-ProviderName <String>] [-AlgorithmName <String>] [-KeyLength <Int32>] [-KeySpec <String> {Exchange | Signature} ] [-EnhancedKeyUsage <Oid[]>] [-KeyUsage <X509KeyUsageFlags>] [-SubjectAlternativeName <String[]>] [-IsCA <Boolean>] [-PathLength <Int32>] [-CustomExtension <X509ExtensionCollection>] [-SignatureAlgorithm <String> {MD5 | SHA1 | SHA256 | SHA384 | SHA512} ] [-AlternateSignatureFormat] [-Issuer <X509Certificate2>] [-FriendlyName <String>] [-Runtime] [-AllowSMIME] [-Exportable] [<CommonParameters>]

New-SelfSignedCertificateEx [-Subject] <String> [[-NotBefore] <DateTime>] [[-NotAfter] <DateTime>] [-SerialNumber <String>] [-ProviderName <String>] [-AlgorithmName <String>] [-KeyLength <Int32>] [-KeySpec <String> {Exchange | Signature} ] [-EnhancedKeyUsage <Oid[]>] [-KeyUsage <X509KeyUsageFlags>] [-SubjectAlternativeName <String[]>] [-IsCA <Boolean>] [-PathLength <Int32>] [-CustomExtension <X509ExtensionCollection>] [-SignatureAlgorithm <String> {MD5 | SHA1 | SHA256 | SHA384 | SHA512} ] [-AlternateSignatureFormat] [-Issuer <X509Certificate2>] [-FriendlyName <String>] [-StoreLocation <StoreLocation>] [-AllowSMIME] [-Exportable] [<CommonParameters>]

New-SelfSignedCertificateEx [-Subject] <String> [[-NotBefore] <DateTime>] [[-NotAfter] <DateTime>] [-SerialNumber <String>] [-ProviderName <String>] [-AlgorithmName <String>] [-KeyLength <Int32>] [-KeySpec <String> {Exchange | Signature} ] [-EnhancedKeyUsage <Oid[]>] [-KeyUsage <X509KeyUsageFlags>] [-SubjectAlternativeName <String[]>] [-IsCA <Boolean>] [-PathLength <Int32>] [-CustomExtension <X509ExtensionCollection>] [-SignatureAlgorithm <String> {MD5 | SHA1 | SHA256 | SHA384 | SHA512} ] [-AlternateSignatureFormat] [-Issuer <X509Certificate2>] [-FriendlyName <String>] -Path <FileInfo> -Password <SecureString> [-AllowSMIME] [-Exportable] [<CommonParameters>]

Description

This cmdlet generates a self-signed or CA-signed certificate with various options.

Note: self-signed certificates (non-CA) should not be used in a production environment, they are generally intended for testing purposes only.

Parameters

-Subject <String>

Specifies the certificate subject in a X500 distinguished name format.
Example: CN=Test Cert, OU=Sandbox

Required? True
Position? 0
Default value
Accept pipeline input? false
Accept wildcard characters? False

-NotBefore <DateTime>

Specifies the date and time when the certificate become valid. By default previous day date is used.

Required? False
Position? 1
Default value Previous day's date
Accept pipeline input? false
Accept wildcard characters? False

-NotAfter <DateTime>

Specifies the date and time when the certificate expires. By default, the certificate is valid for 1 year.

Required? False
Position? 2
Default value 1 year from current day
Accept pipeline input? false
Accept wildcard characters? False

-SerialNumber <String>

Specifies the desired serial number in a hex format.
Example: 01a4ff2

If not specified, serial number is generated automatically.

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-ProviderName <String>

Specifies the Cryptography Service Provider (CSP) name. You can use either legacy CSP and Key Storage Providers (KSP). By default "Microsoft Enhanced Cryptographic Provider v1.0" CSP is used.

Required? False
Position? named
Default value Microsoft Enhanced Cryptographic Provider v1.0
Accept pipeline input? false
Accept wildcard characters? False

-AlgorithmName <String>

Specifies the public key algorithm. By default RSA algorithm is used. RSA is the only algorithm supported by legacy CSPs. With key storage providers (KSP) you can use CNG algorithms, like ECDH. For CNG algorithms you must use full name:
ECDH_P256
ECDH_P384
ECDH_P521

In addition, KeyLength parameter must be specified explicitly when non-RSA algorithm is used.

Required? False
Position? named
Default value RSA
Accept pipeline input? false
Accept wildcard characters? False

-KeyLength <Int32>

Specifies the key length to generate. By default an RSA 2048-bit key is generated.

Required? False
Position? named
Default value 2048
Accept pipeline input? false
Accept wildcard characters? False

-KeySpec <String>

Specifies the public key operations type. The possible values are: Exchange and Signature. Default value is Exchange.

Required? False
Position? named
Default value Exchange
Accept pipeline input? false
Accept wildcard characters? False

-EnhancedKeyUsage <Oid[]>

Specifies the intended uses of the public key contained in a certificate. You can specify either, EKU's friendly name (for example 'Server Authentication') or object identifier (OID) value (for example '1.3.6.1.5.5.7.3.1').

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-KeyUsage <X509KeyUsageFlags>

Specifies restrictions on the operations that can be performed by the public key contained in the certificate. Possible values (and their respective integer values to make bitwise operations) are:
-- EncipherOnly
-- CrlSign
-- KeyCertSign
-- KeyAgreement
-- DataEncipherment
-- KeyEncipherment
-- NonRepudiation
-- DigitalSignature
-- DecipherOnly

you can combine key usages values by using bitwise OR operation. When combining multiple flags, they must be enclosed in quotes and separated by a comma character. For example, to combine KeyEncipherment and DigitalSignature flags you should type: "KeyEncipherment, DigitalSignature".

If the certificate is CA certificate (see IsCA parameter), key usages extension is generated automatically with the following key usages: Certificate Signing, Off-line CRL Signing, CRL Signing.

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-SubjectAlternativeName <String[]>

Specifies alternative names for the subject. Unlike Subject field, this extension allows to specify more than one name. Also, multiple types of alternative names are supported.

The following syntax is used to specify alternative names (curve braces denote alternative name value):
-- DNS name: "dns:{dns_name}". Example: "dns:www.example.com"
-- RFC822 Name: "email:{email_address}". Example: "email:someone@example.com"
-- IP address: "ip:{ipv4_or_ipv6}". Example: "ip:192.168.0.1", "ip:fd00:0:0:4::41"
-- User Principal Name (UPN): "upn:{user_principal_name}". Example: "upn:someone@example.com"
-- Directory name: "dn:{X.500_name}". Example: "dn:CN=Someone, OU=OrgUnit, O=Example Inc., C=US"
-- Object Identifier (OID): "oid:{IANA_assigned_oid}". Example: "oid:1.2.3.4.5.6.99999"
-- URL: "url:{URL}". Example: "url:https://host.example.com/resource.html"
-- GUID: "guid:{GUID}". Example: "guid:42105db6-313e-41be-96ae-52fc4633507f"

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-IsCA <Boolean>

Specifies whether the certificate is Certification Authority (IsCA = $true) or end entity (IsCA = $false) certificate. If this parameter is set to $false, PathLength parameter is ignored. Basic Constraints extension is marked as critical.

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-PathLength <Int32>

Specifies the number of additional CA certificates in the chain under this certificate. If this parameter is set to zero, then no additional (subordinate) CA certificates are permitted under this CA.

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-CustomExtension <X509ExtensionCollection>

Specifies the custom extension to include to a self-signed certificate. This parameter must not be used to specify the extension that is supported via other parameters. In order to use this parameter, the extension must be formed in a collection of initialized System.Security.Cryptography.X509Certificates.X509Extension objects.

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-SignatureAlgorithm <String>

Specifies signature algorithm used to sign the certificate. By default 'SHA1' algorithm is used.

Required? False
Position? named
Default value SHA1
Accept pipeline input? false
Accept wildcard characters? False

-FriendlyName <String>

Specifies friendly name for the certificate.

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-StoreLocation <StoreLocation>

Specifies the store location to store self-signed certificate. Possible values are: 'CurrentUser' and 'LocalMachine'. 'CurrentUser' store is intended for user certificates and computer (as well as CA) certificates must be stored in the 'LocalMachine' store.

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-AllowSMIME <SwitchParameter>

Enables Secure/Multipurpose Internet Mail Extensions for the certificate.

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-Exportable <SwitchParameter>

Marks private key as exportable. Smart card providers usually do not allow exportable keys.

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-Path <FileInfo>

Specifies the path to a PFX file to export a self-signed certificate.

Required? True
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-Password <SecureString>

Specifies the password for PFX file.

Required? True
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-AlternateSignatureFormat <SwitchParameter>

Specifies if PKCS#1 v2.1 signature format is used. When specified, RSA signature will be set to RSASSA-PSS and ECDSA will be set to EcdsaSpecified.

Note: this parameter may not be compatible with all cryptographic libraries.

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-Issuer <X509Certificate2>

Specifies the signer certificate to sign generated certificate. When specified, generated certificate will be CA-signed, not self-signed. Generated certificate will include issuer name in Issuer field and includes AuthorityKeyIdenditier extension with issuer's public key SHA1 hash.

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

-Runtime <SwitchParameter>

Specifies whether the certificate is generated in memory without installing it in Windows Certificate Store. By default, generated certificate is installed in Windows Certificate Store. Use this switch parameter to avoid interaction with Windows Certificate Store. Object returned by this command will be the only reference to the certificate and caller must interact with returned object only.

Required? False
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? False

<CommonParameters>

This cmdlet supports the common parameters: Verbose, Debug,
ErrorAction, ErrorVariable, InformationAction, InformationVariable,
WarningAction, WarningVariable, OutBuffer, PipelineVariable and OutVariable.
For more information, see about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216).

Inputs

None.

Outputs

System.Security.Cryptography.X509Certificates.X509Certificate2

Notes

Author: Vadims Podans
Blog: https://www.sysadmins.lv

Examples

Example 1

PS C:\> New-SelfsignedCertificateEx -Subject "CN=Test Code Signing" -EKU "Code Signing" -KeySpec "Signature" `
 -KeyUsage "DigitalSignature" -FriendlyName "Test code signing" -NotAfter $((Get-Date).AddYears(5))

Creates a self-signed certificate intended for code signing and which is valid for 5 years. Certificate is saved in the Personal store of the current user account.

Example 2

PS C:\> New-SelfsignedCertificateEx -Subject "CN=www.domain.com" -EKU "Server Authentication", "Client authentication" `
 -KeyUsage "KeyEcipherment, DigitalSignature" -SAN "dns:sub.domain.com","dns:www.domain.com","ip:192.168.1.1" `
 -AllowSMIME -Path C:\test\ssl.pfx -Password (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force) -Exportable `
 -StoreLocation "LocalMachine"

Creates a self-signed SSL certificate with multiple subject names and saves it to a file. Additionally, the certificate is saved in the Personal store of the Local Machine store. Private key is marked as exportable, so you can export the certificate with a associated private key to a file at any time. The certificate includes SMIME capabilities.

Example 3

PS C:\> New-SelfsignedCertificateEx -Subject "CN=www.domain.com" -EKU "Server Authentication", "Client authentication" `
 -KeyUsage "KeyEcipherment, DigitalSignature" -SAN "dns:sub.domain.com","dns:www.domain.com","ip:192.168.1.1" `
 -StoreLocation "LocalMachine" -ProviderName "Microsoft Software Key Storage Provider" -AlgorithmName ecdsa_p256 `
 -KeyLength 256 -SignatureAlgorithm sha256

Creates a self-signed SSL certificate with multiple subject names and saves it to a file. Additionally, the certificate is saved in the Personal store of the Local Machine store. Private key is marked as exportable, so you can export the certificate with a associated private key to a file at any time. Certificate uses Ellyptic Curve Cryptography (ECC) key algorithm ECDSA with 256-bit key. The certificate is signed by using SHA256ECDSA algorithm.

Example 4

PS C:\> New-SelfsignedCertificateEx -Subject "CN=Test Root CA, OU=Sandbox" -IsCA $true -ProviderName `
 "Microsoft Software Key Storage Provider" -Exportable

Creates self-signed root CA certificate.

Related links

Minimum PowerShell version support

  • PowerShell 3.0

Operating System Support

  • Windows Vista
  • Windows 7
  • Windows 8
  • Windows 8.1
  • Windows 10
  • Windows Server 2008 all editions
  • Windows Server 2008 R2 all editions
  • Windows Server 2012 all editions
  • Windows Server 2012 R2 all editions
  • Windows Server 2016 all editions

Share this article:

Comments:

Lokesh Jangir
Lokesh Jangir 16.06.2016 09:33 (GMT+3) New-SelfSignedCertificateEx

Hi,

I am using this command to generate self signed certificate -

New-SelfsignedCertificateEx -Subject "CN=Test" -EKU "Code Signing" -FriendlyName "Test" -StoreLocation LocalMachine

it works fine and generates certificate silently. It doesn't give any output as 'New-SelfsignedCertificate' does. Is there any way to capture output of this command so that we can store it's thumbprint, otherwise automation is really difficult if there are multiple certificates available with the same subject and friendly name.

Thanks, Lokesh Jangir
 

Mike Driest
Mike Driest 15.08.2016 15:32 (GMT+3) New-SelfSignedCertificateEx

Hi,

Great work on the PowerShell PKI module!  I ran into an error with New-SelfsignedCertificateEx when I tried to use -Path C:\test\ssl.pfx, -Password, -Exportable, and -StoreLocation "LocalMachine" similar to Example # 2.  It seems you have to omit -StoreLocation in order to be able to export a cert to a path.  I need to store a cert in the Local Machine store with it marked as exportable, and need to export it to a password protected PFX file.

Thank you,

Mike

Mike Driest
Mike Driest 08.04.2017 22:24 (GMT+3) New-SelfSignedCertificateEx

Will the New-SelfsignedCertificateEx work via PSRemoting?  I'm trying to use it in a script with PSRemoting, .e.g. ServerA runs this PSRemoting command against ServerB

Invoke-Command -ScriptBlock {New-SelfsignedCertificateEx -Arguments...} -Computer ServerB -Credentials $SecureCreds

Then I receive this error:

ResultData=Exception calling "Create" with "0" argument(s): "CertEnroll::CX509PrivateKey::Create: The requested operation cannot be completed. The computer must be trusted for delegation and the current user account must be configured to allow delegation. 0x80090345 (-2146892987 SEC_E_DELEGATION_REQUIRED)"}}

If I run my code locally on ServerB without PSRemoting it executes successfully.

Vadims Podāns
Vadims Podāns 12.04.2017 10:43 (GMT+3) New-SelfSignedCertificateEx

You need to use "-EnableNetworkAccess" parameter to use CredSSP authentication and enable interactive token.

krizio
krizio 02.07.2017 12:21 (GMT+3) New-SelfSignedCertificateEx

@Mike Driest, I think you are not using the Inovke-Commands arguments correctly in order to pass arguments inside the -ScriptBlock

have a look on this here https://stackoverflow.com/questions/39843767/powershell-pass-multiple-parameters-to-invoke-command

Kav
Kav 07.08.2018 16:10 (GMT+3) New-SelfSignedCertificateEx

Thank you so much for this!!! MS has unfortunately left Win server 2012R2 high and dry and not provided it the new fully featured new-selfsignedcertificate cmdlet (Win10 and server 2016 only), this is a brilliant solution :)

Marc Este
Marc Este 23.08.2018 10:08 (GMT+3) New-SelfSignedCertificateEx

Hello Vadims,

good to see you moved the code from TechNet gallery to GitHub.

Trying to run this, from an example on securing DSC mof files,

New-SelfsignedCertificateEx `
    -Subject "CN=${ENV:ComputerName}" `
    -EKU "Server Authentication" `
    -KeyUsage 'KeyEncipherment, DataEncipherment' `
    -SAN ${ENV:ComputerName} `
    -FriendlyName 'DSC Credential Encryption certificate' `
    -Exportable `
    -StoreLocation 'LocalMachine' `
    -KeyLength 2048 `
    -ProviderName 'Microsoft Enhanced Cryptographic Provider v1.0' `
    -AlgorithmName 'RSA' `
    -SignatureAlgorithm 'SHA256'

I stumble into an error regarding EnhancedKeyUsage (EKU) parameter which states:

ForEach-Object : CertEnroll::CObjectId::InitializeFromValue: Incorrect parameter

and points to line 89 C:\Program Files\WindowsPowerShell\Modules\PSPKI\3.3.0.0\Client\New-SelfSignedCertificateEx.ps1

+ $EnhancedKeyUsage | ForEach-Object

I cannot see why EKU value "Server Authentication" is wrong

Any help is very much appreciated.

Greetings

 

Marc Esteve
Marc Esteve 23.08.2018 11:29 (GMT+3) New-SelfSignedCertificateEx

I forgot to tell that I checked that Remote System Administration Tools was install.

I tried generating the certificate either in a Server 2008 R2 and a Server 2012, with WFM 5.1 and the aforementioned tools.

I also tried to run an example from Get-help New-SelfSignedCertificateEx -Examples

New-SelfsignedCertificateEx -Subject "CN=www.domain.com" -EKU "Server Authentication", "Client authentication" `
     -KeyUsage "KeyEcipherment, DigitalSignature" -SAN "sub.domain.com","www.domain.com","192.168.1.1" `
     -StoreLocation "LocalMachine" -ProviderName "Microsoft Software Key Storage Provider" -AlgorithmName ecdsa_p256 `
     -KeyLength 256 -SignatureAlgorithm sha256

and got the same EKU-related error.

Marc Esteve
Marc Esteve 23.08.2018 12:01 (GMT+3) New-SelfSignedCertificateEx

I'm sorry about the multiple posts :( I'd rather edit a previous one, but I think there's not an option for this.

EKU was wrong because my S.O language is not English, so the EKU's friendly name must be written using the S.O's language :)

I could found the translation by using OIDs, doing:

$OID = New-Object -ComObject X509Enrollment.CObjectID
$OID.InitializeFromValue('1.3.6.1.5.5.7.3.1')

$OID2 = New-Object -ComObject X509Enrollment.CObjectID
$OID2.InitializeFromValue('1.3.6.1.5.5.7.3.2')

Nevertheless, I now find another problem which is so generic that doesn't give me any clue:

Non-initialized Object (translated error message)

New-SelfsignedCertificateEx : Objeto no inicializable (Excepción de HRESULT: 0x80040007 (OLE_E_BLANK))
At line:3 char:1
+ New-SelfsignedCertificateEx `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [New-SelfSignedCertificateEx], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,New-SelfSignedCertificateEx

 

Vadims Podāns
Vadims Podāns 23.08.2018 19:57 (GMT+3) New-SelfSignedCertificateEx

> EKU was wrong because my S.O language is not English, so the EKU's friendly name must be written using the S.O's language

it is correct, OIDs are localizable. One workaround is to use OID values instead of friendly names.

> Non-initialized Object (translated error message)

Did you made any modifications in the script? Also, I would suggest to review error, or submit it on GitHub (this page is not support portal, it is used only for documentation quality issues).

To read the error, run the command that raises error, then investigate $Error variable:

$error[0].innerexception.psbase

This command will reveal some useful information for debugging. You can submit this information on GitHub.


Post your comment:

Please, solve this little equation and enter result below. Captcha