Windows create certificate self signed certificate

How do I create a self-signed certificate for code signing using tools from the Windows SDK?

Updated Answer

If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then MakeCert is now deprecated, and Microsoft recommends using the PowerShell Cmdlet New-SelfSignedCertificate.

If you’re using an older version such as Windows 7, you’ll need to stick with MakeCert or another solution. Some people suggest the Public Key Infrastructure Powershell (PSPKI) Module.

Original Answer

While you can create a self-signed code-signing certificate (SPC — Software Publisher Certificate) in one go, I prefer to do the following:

Creating a self-signed certificate authority (CA)

makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^
         -a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer

(^ = allow batch command-line to wrap line)

This creates a self-signed (-r) certificate, with an exportable private key (-pe). It’s named «My CA», and should be put in the CA store for the current user. We’re using the SHA-256 algorithm. The key is meant for signing (-sky).

The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.

Importing the CA certificate

Because there’s no point in having a CA certificate if you don’t trust it, you’ll need to import it into the Windows certificate store. You can use the Certificates MMC snapin, but from the command line:

certutil -user -addstore Root MyCA.cer

Creating a code-signing certificate (SPC)

makecert -pe -n "CN=My SPC" -a sha256 -cy end ^
         -sky signature ^
         -ic MyCA.cer -iv MyCA.pvk ^
         -sv MySPC.pvk MySPC.cer

It is pretty much the same as above, but we’re providing an issuer key and certificate (the -ic and -iv switches).

We’ll also want to convert the certificate and key into a PFX file:

pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx

If you are using a password please use the below

pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx -po fess

If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.

Using the certificate for signing code

signtool sign /v /f MySPC.pfx ^
              /t http://timestamp.url MyExecutable.exe

(See why timestamps may matter)

If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:

signtool sign /v /n "Me" /s SPC ^
              /t http://timestamp.url MyExecutable.exe

Some possible timestamp URLs for signtool /t are:

  • http://timestamp.verisign.com/scripts/timstamp.dll
  • http://timestamp.globalsign.com/scripts/timstamp.dll
  • http://timestamp.comodoca.com/authenticode
  • http://timestamp.digicert.com

Full Microsoft documentation

  • signtool
  • makecert
  • pvk2pfx

Downloads

For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: [SDK & .NET][5] (which installs makecert in `C:Program FilesMicrosoft SDKsWindowsv7.1`). Your mileage may vary.

MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under «Developer Command Prompt for VS 2015» or «VS2015 x64 Native Tools Command Prompt» (probably all of them in the same folder).

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

Contents:

  • New-SelfSignedCertificate: Creating a Self-Signed Certificate with PowerShell
  • Create a Certificate with the Subject Alternative Name (SAN) Using PowerShell
  • How to Export a Self-Signed Certificate on Windows?
  • Generating a Self-Signed Certificate for Code Signing on Windows
  • Creating SHA-256 Self-Signed SSL Certificate in IIS on Windows Server

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

To create a self-signed certificate with PowerShell, you can use the built-in New-SelfSignedCertificate 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

It is recommended to use self-signed certificates for testing/developing tasks or to provide certificates for internal Intranet services (IIS, Exchange, Web Application Proxy, LDAPS, ADRMS, DirectAccess, etc.) if you cannot deploy PKI/CA infrastructure or purchase a trusted certificate from an external provider.

To create a certificate, you have to specify the values of –DnsName (name of a server, the name may be arbitrary and even different from the current hostname) and -CertStoreLocation (a local certificate store in which the generated certificate will be placed).

To create a new SSL certificate (with the default SSLServerAuthentication type) for the DNS name test.contoso.com (use an FQDN name) and place it to the personal certificates on a computer, run the following command:

New-SelfSignedCertificate -DnsName test.contoso.com -CertStoreLocation cert:LocalMachineMy

New-SelfSignedCertificate 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 admin 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, using the -KeyAlgorithm "ECDSA_secP256r1" -Provider "Microsoft Smart Card Key Storage Provider"parameters), make sure it is installed on your computer (the default is Microsoft Enhanced 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;
  • 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;
  • Crypto provider: Microsoft Software Key Storage Provider.

This command creates a new certificate and imports it into the computer’s personal certificate store. Open the certlm.msc MMC snap-in and make sure that a new certificate appears in the 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:LocalMachineMy" | Where-Object Thumbprint -eq 2175A76B10F843676951965F52A718F635FFA043 | Select-Object *

list self-signed certificate properties with powershell

PSPath                   : Microsoft.PowerShell.SecurityCertificate::LocalMachineMy2175A76B10F843676951965F52A718F635FFA043
PSParentPath             : Microsoft.PowerShell.SecurityCertificate::LocalMachineMy
PSChildName              : 2175A76B10F843676951965F52A718F635FFA043
PSDrive                  : Cert
PSProvider               : Microsoft.PowerShell.SecurityCertificate
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

Note. This self-signed certificate will expire 1 year after it was created. You can set a different certificate validity period using the –NotAfter option. For example, you can issue an SSL/TLS certificate with a three-year validity period with the following commands:

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

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

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

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

The 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 generate a document encryption certificate to protect your document and email. Use the DocumentEncryptionCert type when creating a cert:

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

Check the certificate EnhancedKeyUsageList value:

$doccert|select EnhancedKeyUsageList

{Document Encryption (1.3.6.1.4.1.311.80.1)}

get certificate enhancedkeyusagelist: document encryption cert

Create a Certificate with the Subject Alternative Name (SAN) Using PowerShell

The New-SelfSignedCertificate cmdlet allows you to create a certificate with several different Subject Alternative Names (SANs).

Note. The Makecert.exetool, unlike the New-SelfSignedCertificate cmdlet, cannot create SAN and Wildcard certificates.[/alert]

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

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

You can the following command to generate a certificate 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:LocalMachineMy

certificate with several Subject Alternative Name

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

New-SelfSignedCertificate -certstorelocation cert:localmachinemy -dnsname *.contoso.com

You can generate a self-signed certificate not only for a DNS hostname, but also for an IP address. To do this, you need to use -TextExtension instead of -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 IP address of the host and its DNS names.

create self-signed certificate for an IP address on windows

How to Export a Self-Signed Certificate on Windows?

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 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:LocalMachineMy2779C7928D055B21AAA0Cfe2F6BE1A5C2CA83B30 -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:LocalMachineMy2779C7928D055B21AAA0Cfe2F6BE1A5C2CA83B30 -FilePath C:tstcert.cer

Make sure the *.CER (PFX) certificate file appears in the specified directory. If you right-click it and select the “Install Certificate” menu item, you can use the Certificate Import Wizard to add the certificate to the trusted root certificates on your computer.

install certificate with file explorer on windows 10

Select Cert Store location -> Local Machine, Place all certificates in the following store -> Trusted Root Certification Authorities.

install certificate to trusted root certification authorities

[alert]You can create a certificate and immediately import it into the Trusted Root Certificate store of the computer using the commands:

$SelfSignCert=New-SelfSignedCertificate …..
$certFile = Export-Certificate -Cert $SelfSignCert -FilePath C:psexport-certname.cer
Import-Certificate -CertStoreLocation Cert:LocalMachineAuthRoot -FilePath $certFile.FullName

You can deploy this public key or the certificate file itself on all user computers and servers in the Active Directory domain using GPO (How to deploy certificates to users with GPO?).

Generating a Self-Signed Certificate for Code Signing on Windows

In PowerShell 3.0, the New-SelfSifgnedCertificate cmdlet only generates SSL certificates which cannot be used to sign the driver code, application, or script (unlike the certificates generated by the MakeCert utility).

You can use the New-SelfSifgnedCertificate cmdlet to issue Code Signing certificates in PowerShell version 5.0 and newer.

In order to create a self-signed certificate for sign application code, run the command:

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

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

Set-AuthenticodeSignature -FilePath C:PSmy_posh_script.ps1 -Certificate $cert

If you are receiving an UnknownError warning when executing the command, this means that the certificate is not trusted, because it is located in the user’s personal certificates store.

signing powershell script using self-signed cert - 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 lists of trusted root certificates).

Move-Item -Path $cert.PSPath -Destination "Cert:CurrentUserRoot"

Now you can 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 (using Create Self-Signed Certificate action 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 create self signed ssl certificate on windows server

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

binding self signed sha256 certificate to iis site on windows server

Open the IIS Manager console (inetmgr.exe), select your site, and then select the certificate you created in the Site Binding options. Save your changes.

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

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

Большинству администраторов Windows, знакомых с темой PKI, известна утилита MakeCert.exe, с помощью которой можно создать самоподписанный сертификат. Эта утилита включена в состав Microsoft .NET Framework SDK и Microsoft Windows SDK. В современных версиях Windows 11/10/8.1 и Windows Server 2022/2019/2016/2012R2 вы можете создать самоподписанный сертификат с помощью встроенных командлетов PowerShell без использования дополнительных утилит.

Содержание:

  • New-SelfSignedCertificate: создать самоподписанный SSL сертификат в PowerShell
  • Как сгенерировать SAN (SubjectAltName) сертификат с помощью PowerShell?
  • Экспорт самоподписаного сертификата в Windows
  • Сгенерировать сертификат для подписи кода типа Code Signing
  • Создать самоподписанный SSL сертификат SHA-256 для IIS

New-SelfSignedCertificate: создать самоподписанный SSL сертификат в PowerShell

Для создания самоподписанного сертификата в PowerShell нужно использовать командлет New-SelfSignedCertificate, входящий в состав модуля PKI (Public Key Infrastructure).

Чтобы вывести список всех доступных командлетов в модуле PKI, выполните команду:

Get-Command -Module PKI

управление самоподписанными сертфикатми встроенным модулем powershell pki

Самоподписанные SSL сертификаты рекомендуется использовать в тестовых целях или для обеспечения сертификатами внутренних интранет служб (IIS, Exchange, Web Application Proxy, LDAPS, ADRMS, DirectAccess и т.п.), в тех случая когда по какой-то причине приобретение сертификата у внешнего провайдера или разворачивание инфраструктуры PKI/CA невозможны.

Совет. Не забывайте, что вы можете использования полноценные бесплатные SSL сертификаты от Let’s Encrypt. Например, вы можете SSL сертификат Let’s Encrypt и привязать его к сайту IIS.

Для создания сертификата нужно указать значения -DnsName (DNS имя сервера, имя может быть произвольным и отличаться от имени localhost) и -CertStoreLocation (раздел локального хранилища сертификатов, в который будет помещен сгенерированный сертификат).

Чтобы создать новый SSL сертификат для DNS имени test.contoso.com (указывается FQDN имя) и поместить его в список персональных сертификатов компьютера, выполните команду:

New-SelfSignedCertificate -DnsName test.contoso.com -CertStoreLocation cert:LocalMachineMy

New-SelfSignedCertificate командлет создать SSL сертификат в Windows

Команда вернет отпечаток нового сертификата (Thumbprint), Subject и EnhancedKeyUsageList. По умолчанию такой сертификат можно использовать для аутентификации клиента Client Authentication (1.3.6.1.5.5.7.3.2) или сервера Server Authentication (1.3.6.1.5.5.7.3.1).

Если вы запустите эту команду в PowerShell без прав администратор, появится ошибка:

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

Если вы указали нестандартный криптографический провайдер CSPs (например, с помощью параметров
-KeyAlgorithm "ECDSA_secP256r1" -Provider 'Microsoft Smart Card Key Storage Provider'
), убедитесь, что он установлен на компьютере (по умолчанию используется CSP Microsoft Enhanced Cryptographic Provider). Иначе появится ошибка:

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

По-умолчанию генерируется самоподписанный сертификат со следующим параметрами:

  • Криптографический алгоритм: RSA;
  • Размер ключа: 2048 бит;
  • Допустимые варианты использования ключа: Client Authentication и Server Authentication;
  • Сертификат может использоваться для: Digital Signature, Key Encipherment ;
  • Срок действия сертификата: 1 год.
  • Криптопровадер: Microsoft Software Key Storage Provider

Данная команда создаст новый сертификат и импортирует его в персональное хранилище компьютера. Откройте оснастку certlm.msc и проверьте, что в разделе Personal хранилища сертификатов компьютера появился новый сертификат.

Самоподписанный сертифкат в разделе личных сертификатов

С помощью командлета Get-ChildItem можно вывести все параметры созданного сертификата по его отпечатку (Thumbprint):

Get-ChildItem -Path "Cert:LocalMachineMy" | Where-Object Thumbprint -eq 76360EAA92D958ECF2717261F75D426E6DB5B4D1 | Select-Object *

вывести параметры самоподписанного сертификата из powershell

PSPath                   : Microsoft.PowerShell.SecurityCertificate::LocalMachineMy76360EAA92D958ECF2717261F75D426E6
                           DB5B4D1
PSParentPath             : Microsoft.PowerShell.SecurityCertificate::LocalMachineMy
PSChildName              : 76360EAA92D958ECF2717261F75D426E6DB5B4D1
PSDrive                  : Cert
PSProvider               : Microsoft.PowerShell.SecurityCertificate
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             :
HasPrivateKey            : True
PrivateKey               : System.Security.Cryptography.RSACng
IssuerName               : System.Security.Cryptography.X509Certificates.X500DistinguishedName
NotAfter                 : 12/2/2023 3:41:18 PM
NotBefore                : 12/2/2022 3:21:18 PM
PublicKey                : System.Security.Cryptography.X509Certificates.PublicKey
 RawData                  : {48, 130, 3, 45…}
SerialNumber             : 24682351DA9C59874573BA2B5BB39874
SignatureAlgorithm       : System.Security.Cryptography.Oid
SubjectName              : System.Security.Cryptography.X509Certificates.X500DistinguishedName
Thumbprint               : 76360EAA92D958ECF2717261F75D426E6DB5B4D1
Version                  : 3
Handle                   : 2007435579936
Issuer                   : CN=test.contoso.com
Subject                  : CN=test.contoso.com 

Примечание. Срок действия такого самоподписанного сертификата истекает через 1 год с момента его создания. Можно задать другой срок действия сертификата с помощью атрибута NotAfter.Чтобы выпустить сертификат на 3 года, выполните следующие команды:

$todaydate = Get-Date
$add3year = $todaydate.AddYears(3)
New-SelfSignedCertificate -dnsname test.contoso.com -notafter $add3year -CertStoreLocation cert:LocalMachineMy

Можно создать цепочку сертификатов. Сначала создается корневой сертификат (CA), а на основании него генерируется SSL сертификат сервера:

$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:LocalMachineMy -DnsName "test2.contoso.com" -Signer $rootCert -KeyUsage KeyEncipherment,DigitalSignature

Чтобы изменить длину ключа сертификата и алгоритм шифрования, нужно использовать параметры
–KeyAlgorithm
,
–KeyLength
и
–HashAlgorithm
. Например:

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

Если на компьютере доступен модуль TPM 2.0, можно использовать его для защиты ключа:

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

Провайдер Microsoft Platform Crypto Provider использует Trusted Platform Module чип устройства для создания ассиметричного ключа.
$Params = @{
"DnsName" = "mylocalhostname"
"CertStoreLocation" = "Cert:\CurrentUser\My"
"KeyUsage" = "KeyEncipherment","DataEncipherment","KeyAgreement"
"Type" = "DocumentEncryptionCert"
}
New-SelfSignedCertificate @Params

Как сгенерировать SAN (SubjectAltName) сертификат с помощью PowerShell?

Командлет New-SelfSignedCertificate позволяет создать сертификат с несколькими различными именами Subject Alternative Names (SAN).

Примечание. Утилита Makecert.exe, в отличии от командлета New-SelfSignedCertificate, не умеет создавать сертификаты с SAN.

Если создается сертификат с несколькими именами, первое имя в параметре DnsName будет использоваться в качестве CN (Common Name) сертификата. К примеру, создадим сертификат, у которого указаны следующие имена:

  • Subject Name (CN): adfs1.contoso.com
  • Subject Alternative Name (DNS): web-gw.contoso.com
  • Subject Alternative Name (DNS): enterprise-reg.contoso.com

Команда создания сертификата будет такой:

New-SelfSignedCertificate -DnsName adfs1.contoso.com,web_gw.contoso.com,enterprise_reg.contoso.com -CertStoreLocation cert:LocalMachineMy

Сертификат на несколько DNS имен

Также можно сгенерировать wildcard сертификат для всего пространства имен домена, для этого в качестве имени сервера указывается *.contoso.com.

New-SelfSignedCertificate -certstorelocation cert:localmachinemy -dnsname *.contoso.com

Вы можете привязать сертификат не только к DNS имени, но и к IP адресу. Для этого вместе параметр -DnsName нужно использовать -TextExtension. Например:

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

Как вы видите, в поле Subject Alternative Name теперь содержится IP адрес.

сгенерировать ssl сертификат для ip адреса

Экспорт самоподписаного сертификата в Windows

Для экспорта полученного сертификата c закрытым ключом в pfx файл, защищенный паролем, нужно получить его отпечаток (Thumbprint). Сначала нужно указать пароль защиты сертификата и преобразовать его в формат SecureString. Значение Thumbprint нужно скопировать из результатов выполнения команды New-SelfSignedCertificate.

$CertPassword = ConvertTo-SecureString -String “YourPassword” -Force –AsPlainText

Export-PfxCertificate -Cert cert:LocalMachineMy2779C0490D558B31AAA0CEF2F6EB1A5C2CA83B30 -FilePath C:test.pfx -Password $CertPassword

Export-PfxCertificate - экспорт сертификата в файлМожно экспортировать открытый ключ сертификата:

Export-Certificate -Cert Cert:LocalMachineMy2779C0490D558B31AAA0CEF2F6EB1A5C2CA83B30 -FilePath C:testcert.cer

Проверьте, что в указанном каталоге появился CER (PFX) файл сертификата. Если щелкнуть по нему правой клавишей и выбрать пункт меню Install Certificate, можно с помощью мастера импорта сертификатов добавить сертификат в корневые доверенные сертификаты компьютера.

установить cer/pfx сертификат с помощью powershell

Выберите Store location -> Local Machine, Place all certificates in the following store -> Trusted Root Certification Authorities.

импорт сертфиката в доверенные корневые сертфикаты компьютера

Можно создать сертификат и сразу импортировать его в доверенные корневые сертификаты компьютера командами:
$cert=New-SelfSignedCertificate …..
$certFile = Export-Certificate -Cert $cert -FilePath C:certname.cer
Import-Certificate -CertStoreLocation Cert:LocalMachineAuthRoot -FilePath $certFile.FullName

Полученный открытый ключ или сам файл сертификата можно распространить на все компьютеры и сервера в домене с помощью GPO (пример установки сертификата на компьютеры с помощью групповых политик).

Сгенерировать сертификат для подписи кода типа Code Signing

В PoweShell 3.0 командлет New-SelfSifgnedCertificate позволял генерировать только SSL сертификаты, которые нельзя было использоваться для подписывания кода драйверов и приложений (в отличии сертификатов, генерируемых утилитой MakeCert).

В версии PowerShell 5 командлет New-SelfSifgnedCertificate теперь можно использовать чтобы выпустить сертификат типа Code Signing.

Вы можете обновить версию PowerShell согласно инструкции.

Для создания самоподписанного сертфиката для подписывания кода приложений, выполните команду:

$cert = New-SelfSignedCertificate -Subject "Cert for Code Signing” -Type CodeSigningCert -CertStoreLocation cert:LocalMachineMy

Теперь можно подписать ваш PowerShell скрипт эти сертификатом:

Set-AuthenticodeSignature -FilePath C:PStest_script.ps1 -Certificate $cert

Если при выполнении команды появится предупреждение UnknownError, значит этот сертификат недоверенный, т.к. находится в персональном хранилище сертификатов пользователя.

Ошибка UnknownError при подписывании PowerShell скрипта самоподписанным сертификатом

Нужно переместить его в корневые сертификаты (не забывайте периодически проверять хранилище сертификатов Windows на наличие недоверенных сертфикатов и обновлять списки корневых сертификатов):

Move-Item -Path $cert.PSPath -Destination "Cert:CurrentUserRoot"

Теперь вы можете использовать этот самоподписанный сертификат для подписи PowerShell скриптов, драйверов или приложений.

Создать самоподписанный SSL сертификат SHA-256 для IIS

Обратите внимание, что при создании самоподписанный сертификат для IIS через консоль Internet Information Manager (пункт меню Create Self-Signed Certificate), создается сертификат с использованием алгоритма шифрования SHA-1. Такие сертификаты многими браузерами считаются недоверенными, поэтому они могут выдавать предупреждение о небезопасном подключении. Командлет New-SelfSignedCertificate позволяет создать более популярный тип сертификата с помощью алгоритма шифрования SHA-256.

сгенерировать самоподписанный сертификат в iis

Вы можете привязать самоподписанный сертификат SHA-256, созданный в PowerShell, к сайту IIS. Если вы с помощью PowerShell создали SSL сертификат и поместили его в хранилище сертификатов компьютера, он будет автоматически доступен для сайтов IIS.

привязать самоподписанный ssl сертфикат к сайту в IIS Manager

Запустите консоль IIS Manager, выберите ваш сайт, затем в настройке Site Binding, выберите созданный вами сертификат и сохраните изменения.

Также можно привязать SSL сертификат к сайту IIS по его отпечатку:

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

Use a command-line tool or third-party software

by Tashreef Shareef

Tashreef Shareef is a software developer turned tech writer. He discovered his interest in technology after reading a tech magazine accidentally. Now he writes about everything tech from… read more


Updated on October 5, 2022

Reviewed by
Vlad Turiceanu

Vlad Turiceanu

Passionate about technology, Windows, and everything that has a power button, he spent most of his time developing new skills and learning more about the tech world. Coming… read more

  • The process of adding an SSL certificate to your website is pretty straightforward, and this guide will help.
  • We also discuss the 3 most efficient ways to either purchase an SSL certificate, use an open-source SSL, or create your own.
  • One of the best ways to generate a self-signed certificate in Windows 10 is to do so via a command line.

Self signed OpenSSL certificate

XINSTALL BY CLICKING THE DOWNLOAD FILE

To fix various PC problems, we recommend DriverFix:
This software will keep your drivers up and running, thus keeping you safe from common computer errors and hardware failure. Check all your drivers now in 3 easy steps:

  1. Download DriverFix (verified download file).
  2. Click Start Scan to find all problematic drivers.
  3. Click Update Drivers to get new versions and avoid system malfunctionings.
  • DriverFix has been downloaded by 0 readers this month.

Adding an SSL certificate to your website is a straightforward process. You can either purchase a third-party SSL certificate and renew it on a yearly basis or use an open-source SSL certificate and create a corn job to renew it every month.

However, for development and testing, you can explore the possibility of creating a self-signed SSL certificate in Windows.

Creating a self-signed certificate is an excellent alternative to purchasing and renewing a yearly certification for testing purposes. You can make use of OpenSSL to generate a self-signed certificate for this purpose.

In this article, we explore how to create a self-signed certificate in Windows 10. The later part of the article also explores how to deploy the self-signed certificate to client machines.

Quick Tip:

Although you can save some money if you create a self-signed certificate, it may lead to a permanent block of your website for some users. This is caused by the certificate error message and in most cases cannot be undone.

Besides that, the process is time-consuming and really not worth your time which also has a certain cost. We strongly recommend using a 3rd party SSL service provider.

GoDaddy SSL Certificates

GoDaddy SSL Certificates

GoDaddy is one of the best web hosting providers that also offers affordable SSL certificates.

How can I generate a self-signed certificate in Windows 10?

1. Use OpenSSL to create a self-signed certificate

1.1 Install OpenSSL

Create a self-signed certificate
  1. Download the latest OpenSSL windows installer from a third-party source.
  2. Run the installer. OpenSSL requires Microsoft Visual C++ to run. The installer will prompt you to install Visual C++ if it is already not installed.
  3. Click Yes to install.
  4. Run the OpenSSL installer again and select the installation directory.
  5. Click Next.
  6. Open a command prompt and type OpenSSL to get OpenSSL prompt.

1.2 Create a public/private key file pair

Create a self-signed certificate command prompt
  1. Make sure you have OpenSSL installed.
  2. Open Command Prompt and create a new directory on your C drive:
    C: >cd Test
  3. Now go to the new directory:
    C: Test>
  4. Now you need to type the path of the OpenSSL install directory followed by the RSA key algorithm.
    C: Test>c:opensslbinopenssl genrsa -out privkey.pem 4096
  5. Run the following command to split the generated file into separate private and public key files:

C: Test>c:opensslbinopenssl ssh-keygen -t rsa -b 4096 -f privkey.pem

Once you have the public/private key generated, follow the next set of steps to create a self-signed certificate file on a Windows system.

1.3 Generate a self-signed certificate

generate a self-signed certificate via command prompt
  1. Open a Command Prompt window.
  2. Go to the directory that you created earlier for the public/private key file.
    C: Test>
  3. Enter the path of the OpenSSL install directory, followed by the self-signed certificate algorithm:
    C: Test>c:opensslbinopenssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095
  1. Follow the on-screen instruction.
  2. You need to enter information about your organization, region, and contact details to create a self-signed certificate.

If you would rather use PowerShell to create a self-signed certificate, follow the next set of steps instead.


2. Generate a Self-Signed Certificate on Windows using PowerShell

1. Press the Windows key, and type Powershell in the search box. Right-click on the PowerShell app and select Run as Administrator.

powershell windows 11 run as admin

2. Run the New-SelfsignedCertificate command, as shown below:$cert = New-SelfSignedCertificate -certstorelocation cert:localmachinemy -dnsname testcert.windowsreport.com

Create a self-signed certificate

Some PC issues are hard to tackle, especially when it comes to corrupted repositories or missing Windows files. If you are having troubles fixing an error, your system may be partially broken.
We recommend installing Restoro, a tool that will scan your machine and identify what the fault is.
Click here to download and start repairing.

3. This will add the certificate to the locater store on your PC. Replace testcert.windowsreport.com with your domain name in the above command.

4. Next, create a password for your export file:$pwd = ConvertTo-SecureString -String ‘password!’ -Force -AsPlainText

5. Replace Password with your own password.

6. Enter the following command to export the self-signed certificate:$path = 'cert:localMachinemy' + $cert.thumbprint Export-PfxCertificate -cert $path -FilePath c:tempcert.pfx -Password $pwd

7. In the above command replace c:temp with the directory where you want to export the file.

8. You can import the exported file and deploy it for your project.

Another great option to generate a self-signed certificate on Windows 10 is to use a command-line tool such as Powershell.

With it, you don’t need to download any third-party software. You just need to input the appropriate command line in Powershell, and the tool will do the job for you.


How to add my self-signed certificate into the curls ca file on Windows 10?

Self Signed OpenSSL certificate
  1. Once you have created a self-signed certificate and installed it, you may want cURL to trust the certificate as well.
  2. The later versions of cURL don’t include a trusted listed a .pem file. You can download the .pem file and type the following command in the php.ini file.
    curl.cainfo = "C:xamppphpcacert.pem"
  3. Once done, you need to get cURL to trust your self-signed certificate. To do this, open your server.crt file. The file is created when you created your self-signed certificate.
  4. Copy all the content of the server.crt file and then add it to the cacert.pem file.

Creating a self-signed certificate using OpenSSL can be done using the Command Prompt or PowerShell. Being able to create your self-signed certificate allows you to create a temporary certificate for in-development projects that require an SSL certificate.

We hope you managed to generate a self-signed certificate on your Windows 10 PC. Let us know in the comments section which method you prefer to use.

Still having issues? Fix them with this tool:

SPONSORED

If the advices above haven’t solved your issue, your PC may experience deeper Windows problems. We recommend downloading this PC Repair tool (rated Great on TrustPilot.com) to easily address them. After installation, simply click the Start Scan button and then press on Repair All.

newsletter icon

Newsletter

Self-signed certificates are widely used in testing environments and they are excellent alternatives to purchasing and renewing yearly certifications.

That is of course if you know how and, more importantly, when to use them. Remember, that A self-signed certificate is not signed by a publicly trusted Certificate Authority (CA). Self-signed certificates are considered different from traditional CA certificates that are signed and issued by a CA because self-signed certificates are created, issued, and signed by the company or developer who is responsible for the website or software associated with the certificate.

You are probably reading this article because for some reason, you need to create a self-signed certificate with Windows. So, we’ve tried to outline the easiest ways to do that. This article is up-to-date as of December 2021. By the way, we’re referring to Windows 10 for all the following tutorials. As far as we know, the processes for Windows 11 are identical.

So what are our options?

Using Let’s Encrypt.

These guys offer free CA certificates with various SAN and wildcard support. The certificate is only good for 90 days, but they do give an automated renewal method. This is a great alternative for a quick proof-of-concept. Other options would require more typing, for sure.

But this option works only if you want to generate a certificate for your website. The best way to start is by going to Getting Started, the instructions thereafter are very easy to follow.

Other one-click option:

We’ve reviewed different online services that allow you to easily generate self-signed certificates. We’ve sorted them from one-click to advanced, and the first one is:

Selfsignedcertificate.com

Just enter your domain name — and you are ready to go:

Getacert.com

Fill out the following fields:

Press “Next”, then confirm your details, and get your certificate:

It’s that easy!

Сertificatetools.com

Among the online services that allow you to generate self-signed certificates, this one is the most advanced; just look at all available options to choose from:

Now let’s continue with offline solutions, that are a bit more advanced:

PowerShell 4.0

1. Press the Windows key, type Powershell. Right-click on PowerShell and select Run as Administrator.

2. Run the New-SelfsignedCertificate command, as shown below.

$cert = New-SelfSignedCertificate -certstorelocation 
cert:localmachinemy -dnsname passwork.com

3.  This will add the certificate to the locater store on your PC. Replace         passwork.com with your domain name in the above command.

4.  Next, create a password for your export file:

$pwd = ConvertTo-SecureString -String ‘password!’ -Force -AsPlainText

5.  Replace password with your own password.

6.  Enter the following command to export the self-signed certificate:

$path = 'cert:localMachinemy' + $cert.thumbprint 
Export-PfxCertificate -cert $path -FilePath 
c:tempcert.pfx -Password $pwd

7. In the above command, replace c:temp with the directory where you want to export the file.

8. Import the exported file and deploy it for your project.

Use OpenSSL

1. Download the latest OpenSSL windows installer from a third-party source;

2. Run the installer. OpenSSL requires Microsoft Visual C++ to run. The installer will prompt you to install Visual C++ if it is already not installed;

3. Click Yes to install;

4. Run the OpenSSL installer again and select the installation directory;

5. Click Next;

6. Open Command Prompt and type OpenSSL to get an OpenSSL prompt.

The next step would be to generate a public/private key file pair.

1. Open Command Prompt and create a new directory on your C drive:

C: >cd Test

2. Now go to the new directory:

C: Test>

3. Now you need to type the path of the OpenSSL install directory followed by the RSA key algorithm:

C: Test>c:opensslbinopenssl genrsa -out privkey.pem 4096

4. Run the following command to split the generated file into separate private and public key files:

C: Test>c:opensslbinopenssl ssh-keygen -t rsa -b 4096 -f privkey.pem

Once you have the public/private key generated, follow the next set of steps to create a self-signed certificate file on Windows.

1. Go to the directory that you created earlier for the public/private key file:

C: Test>

2. Enter the path of the OpenSSL install directory, followed by the self-signed certificate algorithm:

C: Test>c:opensslbinopenssl req -new -x509 -key privkey.pem -out cacert.pem -days 109

3. Follow the on-screen instructions;

4. You need to enter information about your organization, region, and contact details to create a self-signed certificate.

We also have a detailed article on OpenSSL – it contains more in-depth instructions on generating self-signed certificates.

Using IIS

This is one of those hidden features that very few people know about.

1. From the top-level in IIS Manager, select “Server Certificates”;

2. Then click the “Create” button on the right;

3. This will create a self-signed certificate, valid for a year with a private key. It will only work for “localhost”.

We hope this fruit bowl of options provides you with some choice in the matter. Creating your own self-signed certificate nowadays is trivial, but only until you begin to understand how they really work.

Our option of choice is, of course, OpenSSL — after all, it is an industry-standard.

In this guide, we have given step-by-step guides on how to create self-signed certificates using the OpenSSL utility. You can create self-signed certificates using commands or automate them using a shell script by following this guide.

Openssl is a handy utility to create self-signed certificates. You can use OpenSSL on all the operating systems such as Windows, MAC, and Linux flavors.

What is a Self Signed Certificate?

A self-signed certificate is an SSL/TSL certificate not signed by a public or private certificate authority. Instead, it is signed by the creator’s own personal or root CA certificate.

Here is what we do to request paid SSL/TLS certificate from a well-known Certificate Authority like Verisign or comodo.

SSL/TLS certificate request flow.

  1. Create a certificate signing request (CSR) with a private key. A CSR contains details about location, organization, and FQDN (Fully Qualified Domain Name).
  2. Send the CSR to the trusted CA authority.
  3. The CA authority will send you the SSL certificate signed by their root certificate authority and private key.
  4. You can then validate and use the SSL certificate with your applications.

But for a self-signed certificate, here is what we do.

self-signed SSL/TLS certificate creation workflow.

  1. Create our own root CA certificate & CA private key (We act as a CA on our own)
  2. Create a server private key to generate CSR
  3. Create an SSL certificate with CSR using our root CA and CA private key.
  4. Install the CA certificate in the browser or Operating system to avoid security warnings.

Most browsers & operating systems hold a copy of root CA certificates of all the trusted certified Certificated Authorities. That’s the reason the browsers won’t show any security messages when you visit standard websites that use SSL from a trusted and well-known commercial Certificate authority.

The following image shows the root CA present in the Firefox browser by default.

default root CA certificate available in browsers.

At the same time, if you use a self-signed certificate, your browser will throw a security warning. The reason is browsers only trust SSL from a trusted Certificate authority. For example,

Your connection is not private
Attackers might be trying to steal your information from demo.apps.mlopshub.com (for example, passwords, messages or credit cards)

But you can force browsers & operating systems to accept our own certificate authority. So you won’t see the security warning once you install the CA certificate and add it to the trusted list. You can also share the CA certificate with your development team to install in their browsers as well.

Also, you can use this CA to create more than one SSL certificate.

Create Certificate Authority

As discussed earlier, we need to create our own root CA certificate for browsers to trust the self-signed certificate. So let’s create the root CA certificate first.

Let’s create a directory named openssl to save all the generated keys & certificates.

mkdir openssl && cd openssl

Execute the following openssl command to create the rootCA.keyand rootCA.crt. Replace demo.mlopshub.com with your domain name or IP address.

openssl req -x509 
            -sha256 -days 356 
            -nodes 
            -newkey rsa:2048 
            -subj "/CN=demo.mlopshub.com/C=US/L=San Fransisco" 
            -keyout rootCA.key -out rootCA.crt 

We will use the rootCA.keyand rootCA.crt to sign the SSL certificate.

Note: If you get the following error, comment RANDFILE = $ENV::HOME/.rnd line in /etc/ssl/openssl.cnf

Can't load /home/vagrant/.rnd into RNG

Follow the steps given below to create the self-signed certificates. We will sign out certificates using our own root CA created in the previous step.

1. Create the Server Private Key

openssl genrsa -out server.key 2048

2. Create Certificate Signing Request Configuration

We will create a csr.conf file to have all the information to generate the CSR. Replace demo.mlopshub.com with your domain name or IP address.

cat > csr.conf <<EOF
[ req ]
default_bits = 2048
prompt = no
default_md = sha256
req_extensions = req_ext
distinguished_name = dn

[ dn ]
C = US
ST = California
L = San Fransisco
O = MLopsHub
OU = MlopsHub Dev
CN = demo.mlopshub.com

[ req_ext ]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = demo.mlopshub.com
DNS.2 = www.demo.mlopshub.com
IP.1 = 192.168.1.5
IP.2 = 192.168.1.6

EOF

3. Generate Certificate Signing Request (CSR) Using Server Private Key

Now we will generate server.csr using the following command.

openssl req -new -key server.key -out server.csr -config csr.conf

Now our folder should have three files. csr.conf, server.csr and server.key

4. Create a external file

Execute the following to create cert.conf for the SSL certificate. Replace demo.mlopshub.com with your domain name or IP address.

cat > cert.conf <<EOF

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = demo.mlopshub.com

EOF

5. Generate SSL certificate With self signed CA

Now, execute the following command to generate the SSL certificate that is signed by the rootCA.crt and rootCA.key created as part of our own Certificate Authority.

openssl x509 -req 
    -in server.csr 
    -CA rootCA.crt -CAkey rootCA.key 
    -CAcreateserial -out server.crt 
    -days 365 
    -sha256 -extfile cert.conf

The above command will generate server.crt that will be used with our server.key to enable SSL in applications.

For example, the following config shows the Nginx config using the server certificate and private key used for SSL configuration.

server {

listen   443;

ssl    on;
ssl_certificate    /etc/ssl/server.crt;
ssl_certificate_key    /etc/ssl/server.key;

server_name your.domain.com;
access_log /var/log/nginx/nginx.vhost.access.log;
error_log /var/log/nginx/nginx.vhost.error.log;
location / {
root   /home/www/public_html/your.domain.com/public/;
index  index.html;
}

}

Install Certificate Authority In Your Browser/OS

You need to install the rootCA.crt in your browser or operating system to avoid the security message that shows up in the browser when using self-signed certificates.

Installing self-signed CA certificates differs in Operating systems. For example, in MAC, you can add the certificate by double-clicking it and adding it to the keychain. Check the respective Operating system guide on installing the certificate.

  1. For MAC check this guide
  2. Adding certificate to chrome on Windows

Shell Script To Create Self-Signed Certificate

If you want to create self-signed certificates quite often, you can make use of the following shell script. You just need to execute the script with the domain name or IP that you want to add to the certificate.

Save the following shell script as ssl.sh

#! /bin/bash

if [ "$#" -ne 1 ]
then
  echo "Error: No domain name argument provided"
  echo "Usage: Provide a domain name as an argument"
  exit 1
fi

DOMAIN=$1

# Create root CA & Private key

openssl req -x509 
            -sha256 -days 356 
            -nodes 
            -newkey rsa:2048 
            -subj "/CN=${DOMAIN}/C=US/L=San Fransisco" 
            -keyout rootCA.key -out rootCA.crt 

# Generate Private key 

openssl genrsa -out ${DOMAIN}.key 2048

# Create csf conf

cat > csr.conf <<EOF
[ req ]
default_bits = 2048
prompt = no
default_md = sha256
req_extensions = req_ext
distinguished_name = dn

[ dn ]
C = US
ST = California
L = San Fransisco
O = MLopsHub
OU = MlopsHub Dev
CN = ${DOMAIN}

[ req_ext ]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = ${DOMAIN}
DNS.2 = www.${DOMAIN}
IP.1 = 192.168.1.5 
IP.2 = 192.168.1.6

EOF

# create CSR request using private key

openssl req -new -key ${DOMAIN}.key -out ${DOMAIN}.csr -config csr.conf

# Create a external config file for the certificate

cat > cert.conf <<EOF

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = ${DOMAIN}

EOF

# Create SSl with self signed CA

openssl x509 -req 
    -in ${DOMAIN}.csr 
    -CA rootCA.crt -CAkey rootCA.key 
    -CAcreateserial -out ${DOMAIN}.crt 
    -days 365 
    -sha256 -extfile cert.conf

Set the script executable permission by executing the following command.

chmod +x ssl.sh

Execute the script with the domain name or IP. For example,

./ssl.sh demo.mlopshub.com

The script will create all the certificates and keys we created using the individual commands. The SSL certificate and private keys get named with the domain name you pass as the script argument. For example, demo.mlopshub.com.key & demo.mlopshub.com.crt

What are the benefits of using a self-signed certificate?

There are several benefits of using a self-signed certificate:

  1. You don’t need to rely on a third party to sign your certificate.
  2. You can create and use your own certificate authority.
  3. You don’t have to pay for a certificate from a CA.
  4. You have more control over your certificates.

What are the drawbacks of using a self-signed certificate?

There are also several drawbacks of using a self-signed certificate:

  1. Your users will need to install the certificate in their browsers or applications.
  2. Your users will need to trust your certificate authority manually.
  3. They unsafe for public facing applications.
  4. None of the browsers or operating systems trust the self-signed certificates unless the user installs them.
  5. Prone to man-in-the-middle attacks.

In general, self-signed certificates are a good option for applications in which you need to prove your own identity. They’re also a good option for development and testing environments. However, they shouldn’t be used for production applications.

Self-Signed Certificates in Organizations

Many organizations use self-signed certificated for their internal applications that are not internet-facing. These certificates are generated using the organization’s internal PKI infrastructure.

DevOps teams and developers can request SSL certificates from the PKI infrastructure to be used in applications.

Self-Signed Certificate FAQ’s

How to create self-signed certificated on Windows?

You can create a self-signed certificate on windows using Openssl. The OpenSSL commands are the same for all operating systems. You can follow this guide to create a self-signed certificate on windows using this guide.

How do I get a self-signed certificate?

Self-signed certificate can be generated by you using tools like openSSL or CDSSL PKI toolkit.

Conclusion

In this guide, we have learned how to create self-signed SSL certificates using OpenSSL.

For production use cases, if you don’t want to spend money on SSL certificates, you can try out Letsencrypt.

Hope this self-signed SSL guide was helpful with the script to automate the certificate generation. Do let us know if you face any issues.

Also, SSL/TLS is one of the important topics in DevOps. You can check out the how to become a devops engineer blog to know more.

We need to a create self-signed certificate for local development so that the local development server behaves similar to a live production server. Additionally the certificate must not generate warnings in the browser (Chromium based browsers only) that the certificate is self-signed and can’t be trusted.

Developing locally with plain http is just fine. But sometimes we need to mimic development with production so that TLS encryption via https is available also on our development machines. We also don’t want to see ugly security warnings from browsers. The following article shows how to create self-signed certificates on Windows that doesn’t generate browser warnings on Chrome and other Chromium based browsers.

The article is a bit long but please grab a coffee and follow along. The result is worth the effort as you only need to generate the certificate once in a very long time. I set the expiry date 10 years in the future for the domains I create for local development.

Goal: Create an imaginary domain pdb.oak.san with a self-signed certificate that works on major browsers (except Firefox) without generating a warning. Works great on Chromium based browsers like Chrome, Canary, Microsoft Edge and Opera, IE.

Step 1: Setup hostname

  • Open Notepad in Administrator mode: Click Windows Start icon in task bar and start typing Notepad, right click the Notepad icon and click Run as administrator

  • Inside Notepad, open the file: C:WindowsSystem32driversetchosts
  • We want to create an imaginary domain: pdb.oak.san, add the following line to the hosts file:
  • Save the file and close

Step 2: Create a client-side self-signed certificate

  • Open PowerShell in Administrator mode: Click Windows Start icon in task bar and start typing PowerShell, right click the PowerShell icon and click Run as administrator

  • Type the following to generate a self-signed certificate for domain pdb.oak.san with friendly name pdb.oak.san that expires after 10 years:
New-SelfSignedCertificate -CertStoreLocation Cert:LocalMachineMy -DnsName "pdb.oak.san" -FriendlyName "pdb.oak.san" -NotAfter (Get-Date).AddYears(10)
  • You should get the following output

Step 3: Copy the certificate created in Step 2 to Trusted Root Certification Authorities, then export it

  • Open Management Console for Certificates: Click Windows Start icon and start typing certificates, click Manage computer certificates

  • On the left panel, click Personal -> Certificates, you should see the client-side certificate for pdb.oak.san created above in Step 2

  • On the left panel, open the tree for (but don’t left click the folder) Certification Authorities -> Certificates

  • With the right mouse button, drag and drop the certificate to the location opened in the previous step

  • Now export the certificate: right-click the certificate, All Tasks -> Export…

  • Welcome screen appears, click Next
  • Select Yes, export the private key, click Next

  • Keep the default values for .PFX, click Next

  • Type a password for the private key, click Next

  • Browse for a location and give the certificate a name (cert.pfx), click Next

  • Finally click Finish

  • You will get a notice that the export was successful

Step 4: Create the server-side certificate and key

  • Pre-requisite: you need to have OpenSSL https://www.openssl.org/ installed. Since you are a developer and on Windows, it’s highly likely you already have https://git-scm.com/ installed, so you should also have OpenSSL installed. Otherwise we recommend installing Git for Windows with Git Bash support – this will automatically also install OpenSSL.
  • Open Command Prompt and change directory to the location where you exported the certificate with .PFX extension cert.pfx in Step 3 above.
  • Type the following commands in the Command Prompt one by one. When prompted for password, type the password you used in Step 3 above when exporting the .PFX certificate.
$ openssl pkcs12 -in cert.pfx -nocerts -out key.pem -nodes
$ openssl pkcs12 -in cert.pfx -nokeys -out cert.pem
$ openssl rsa -in key.pem -out server.key

  • You should now have the following files in the folder, we will be using the cert.pem and server.key files. You can delete the other files if you want to.
cert.pem    --> KEEP
server.key  --> KEEP
cert.pfx  
key.pem  

Step 5: Test

  • You can use Apache or Nginx to test the https connection for the pdb.oak.san domain. We will create a simple Go server as it can be created really fast with a few lines of code. Create a file called main.go and type the code below. Make sure cert.pem and server.key is in the same folder as the main.go file.
package main

import (
    "fmt"
    "net/http"
)

func handleHome(w http.ResponseWriter, r *http.Request) {
    _, _ = fmt.Fprintln(w, "Home page to test the TLS cert and secure https connection")
}

func main() {
    http.HandleFunc("/", handleHome)
    s:=http.Server{}
    _ = s.ListenAndServeTLS("cert.pem", "server.key")
}
  • Build and run the Go server: go build main.go, then run the resulting executable program main.exe
  • Now if we visit https://pdb.oak.san/ in a browser, we can see the home page with the following content: “Home page to test the TLS cert and secure https connection”

  • We can also check the certificate by clicking on the lock icon in the browser address bar:

For Nginx Users

To test on Nginx instead of writing Go code, you can use the configuration below.

  • Make sure to copy your cert.pem and server.key to the locations for ssl_certificate and ssl_certificate_key.
  • Folder paths like C:Userssanjipdnpdb.oak.sanwww should of course match the locations in your own computer.
server {
    listen          443 ssl;

    server_name     pdb.oak.san;
    root            C:Userssanjipdnpdb.oak.sanwww;
    access_log      C:Userssanjipdnpdb.oak.sanlogsaccess.log;
    error_log       C:Userssanjipdnpdb.oak.sanlogserror.log;
    index           index.html;

    ssl_certificate     C:Userssanjipdnpdb.oak.sansslcert.pem;
    ssl_certificate_key C:Userssanjipdnpdb.oak.sansslserver.key;
}

The video below shows the steps I took to setup SSL on an imaginary domain on my local machine. The video is 20 minutes; maybe I could have been done the video in 10 minutes or less. But here I am showing the actual problems I am running into and the steps I am taking to solve them.

Setting up domains, servers and certificates in real-life is not without problems. This is not a scripted video. It shows the problems I face and how I resolve them.

This a scenario where you have created personal certificates and digitally signed them on your own and now you want them available and trusted on another machine.

Download PC Repair Tool to quickly find & fix Windows errors automatically

SSL is important these days as browsers warn about it if it’s not available on the website. This is applicable for local sites, i.e., websites you host on the computer for testing purposes. Purchasing an SSL certificate for the local site is not of much use, and you can instead create self-signed SSL certificates in Windows 11/10 for such sites. This post will guide you through the process.

Create Local Certificate in Windows 10

Open a PowerShell window with admin privileges. Execute the following command. Make sure to set the exact site name you plan to use on the local computer,

New-SelfSignedCertificate -CertStoreLocation Cert:LocalMachineMy -DnsName "mylocalsite.local" -FriendlyName "MyLocalSiteCert" -NotAfter (Get-Date).AddYears(10)

If you want to test all the original certificate parameters, you can use the CloneCert parameter —more on the official document.

Read: How to manage Trusted Root Certificates in Windows 10.

How to apply or install the certificate on the local website on the computer

Once you have the certificate, you will need to install the computer certificate so browsers can find it. You will need to copy it to the Trusted Root Certification Authorities store.

In the Start Menu, type Manage computer certificates and click to open the Local computer certificates storehouse. You will need admin permission to complete the process.

Install Local SSL Certificate

  • Navigate to Certificates – Local Computer > Personal > Certificates. This place stores all the local certificate that is created on the computer.
  • Find the certificate you have created.
  • Next, on the left panel, expand  Trusted Root Certification Authorities  > Certificates.
  • Drag and drop the local certificate and drop into this folder
  • You can also copy and paste it.

How to create Self-signed SSL Certificates in Windows 10

Once done, make sure to access the local site with HTTPS instead of HTTP. You may have to make the changes to the webserver so any time the local site is accessed, it redirects to the secured version.

I hope the post helped you create a local SSL certificate and install it on the computer, so the browsers don’t warn about the missing encryption.

Read: Difference between TLS and SSL encryption methods.

Ezoic

Ashish is a veteran Windows and Xbox user who excels in writing tips, tricks, and features on it to improve your day-to-day experience with your devices. He has been a Microsoft MVP (2008-2010).

Like this post? Please share to your friends:
  • Windows cpu by zabbix agent active
  • Windows could not start the агент сервера 1с ошибка 1069
  • Windows could not start the sql server
  • Windows could not start the service on local computer error 1053
  • Windows could not start the installation process