Ssl self signed certificate windows

Большинству администраторов 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:\LocalMachine\My

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:\LocalMachine\My" | Where-Object Thumbprint -eq 76360EAA92D958ECF2717261F75D426E6DB5B4D1 | Select-Object *

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

PSPath                   : Microsoft.PowerShell.Security\Certificate::LocalMachine\My\76360EAA92D958ECF2717261F75D426E6
  DB5B4D1
PSParentPath             : Microsoft.PowerShell.Security\Certificate::LocalMachine\My
PSChildName              : 76360EAA92D958ECF2717261F75D426E6DB5B4D1
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             :
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:\LocalMachine\My

Можно создать цепочку сертификатов. Сначала создается корневой сертификат (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:\LocalMachine\My -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:\LocalMachine\My

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

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

New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -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:\LocalMachine\My\2779C0490D558B31AAA0CEF2F6EB1A5C2CA83B30 -FilePath C:\test.pfx -Password $CertPassword

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

Export-Certificate -Cert Cert:\LocalMachine\My\2779C0490D558B31AAA0CEF2F6EB1A5C2CA83B30 -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:\LocalMachine\AuthRoot -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:\LocalMachine\My

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

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

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

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

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

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

Теперь вы можете использовать этот самоподписанный сертификат для подписи 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:\LocalMachine\My" -Protocol https

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.

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

  • 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

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.

How we test, review and rate?

We have worked for the past 6 months on building a new review system on how we produce content. Using it, we have subsequently redone most of our articles to provide actual hands-on expertise on the guides we made.

For more details you can read how we test, review, and rate at WindowsReport.

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

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.

newsletter icon

In the IT world, securing your infrastructure applications and domains is crucial. And to achieve the ideal level of security, you need an SSL certificate. But how do you get an SSL certificate? One of the easiest and most cost-effective ways is to create self-signed certificates on your systems.

Self-signed certificates are public-key certificates that users can generate themselves rather than being issued by a certificate authority. And in this tutorial, you’ll learn how to generate a self-signed certificate on both Windows and Linux machines (for free).

Read on and start securing your apps and infrastructure!

Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:

  • A Windows 10+ device.
  • An Ubuntu machine at least 14.04.4 LTS – This tutorial uses Ubuntu 20.04.4 LTS.
  • Apache installed on Windows and Linux machines.
  • OpenSSL installed on your Windows machine – This tutorial uses OpenSSL 3.0.3 Light (32-bit).

Generating a Self-Signed Certificates on Ubuntu

The easiest way to test the self-signed certificate is on a web server, and one of the most widely used web servers is Apache. So Let’s kick off this tutorial by configuring the Apache server already installed on the Ubuntu machine.

1. SSH into your Ubuntu VM using your favorite SSH client.

2. Run the apt update command below to ensure that Ubuntu has all the latest package sources.

Updating the package repository on the Ubuntu Machine
Updating the package repository on the Ubuntu Machine

3. Next, open your favorite web browser, navigate to <server-ip-address>:80, and you’ll see the Apache homepage opens only on the HTTP port (Not secure).

Verifying the Apache default page
Verifying the Apache default page

4. Now, run each command below to create a directory named ~/certificates and change to that directory where you’ll store certificates.

mkdir ~/certificates
cd ~/certificates

5. Next, run the following openssl command to generate a Certificate Signing Request (CSR ) and a private key.

openssl req -x509 -newkey rsa:4096 -keyout apache.key -out apache.crt -days 365 -nodes

Once you execute the command, enter the details, as shown below.

Generating a CSR and private key
Generating a CSR and private key

Securing the Apache Server with SSL Certificate in Ubuntu

After generating your certificates, you’ll have to configure the Apache server to use the certificates. But first, you need a dedicated directory to hold your certificate. You’ll enable the SSL module later and test if the certificates work in securing your Apache server.

1. Run the following commands to create a directory (/etc/apache2/ssl) and move the certificates from the ~/certificates/ directory to the /etc/apache2/ssl directory.

mkdir /etc/apache2/ssl
mv ~/certificates/* /etc/apache2/ssl/.

2. Open the default SSL Apache site configuration file (/etc/apache2/sites-available/default-ssl.conf) and add the below lines. Be sure to replace <my-server-name> with your server’s actual name.

In the below code, you specify the (certificate key and file) location where you previously copied your certificates.

ServerName <my-server-name>
SSLCertificateFile    /etc/apache2/ssl/apache.crt
SSLCertificateKeyFile /etc/apache2/ssl/apache.key
ProxyPreserveHost On
Updating default SSL Apache site configuration file
Updating default SSL Apache site configuration file

3. Now, run each command below to enable the SSL module, enable the site you modified (step four), and restart the Apache service.

# Enable the SSL module so that you can work with SSL connections.
sudo a2enmod ssl proxy proxy_http proxy_balancer
# Enable the site you modified (step four)
sudo a2ensite default-ssl.conf
# Restart the Apache service
sudo service apache2 restart
Updating the Apache Web server modules and sites and restarting the apache service
Updating the Apache Web server modules and sites and restarting the apache service

4. Finally, navigate to your Apache server again. But this time, using HTTPS, as shown below.

As you can see, Apache is successfully opening with SSL connections on an HTTPS port. Don’t worry if you see a warning symbol displaying the Not secure message. You’ll get that warning since you’re using a self-signed certificate (created by you) and not by the certificate authority.

Click on Proceed to <server-ip> (unsafe) to continue accessing the Apache server.

Accessing the Apache web server on HTTP URL
Accessing the Apache web server on HTTP URL

Do you see the same page as shown below? Congratulations! You’ve successfully secured the Apache server with your self-signed certificate.

Verifying secure Apache server access
Verifying secure Apache server access

Generating an SSL Certificate in Windows

Previously you secured an Apache server hosted on an Ubuntu machine using a self-signed certificate. In the same way, you can also secure the Apache server on a Windows OS.

To secure your Apache server on Windows:

1. Open the Apache configuration file (httpd.conf) at C:\Apache24\conf location and uncomment the below line.

The following line enables the SSL module on Windows machines and allows Apache to work with the HTTPS port.

LoadModule rewrite_module modules/mod_rewrite.so

2. Next, open PowerShell as administrator, and run the following openssl command to generate a Certificate Signing Request (CSR ) and a private key.

openssl req -x509 -newkey rsa:4096 -keyout Apache.key -out Apache.crt -days 365 -nodes

After running the command, enter the details for your certificate, as shown below.

Generating a CSR and private key
Generating a CSR and private key

3. Navigate to the OpenSSL installation bin directory (C:\ProgramFiles\OpenSSL-Win64\bin) and verify the Apache certificate and key below.

Verifying certificates generated on Windows machine
Verifying certificates generated on Windows machine

Configuring the Apache Server to Use SSL Certificates

You’ve just generated your certificate and key to secure the Apache server connection. But like with Ubuntu, you need a dedicated folder to hold your certificate and key and enable the SSL module.

1. Copy your SSL certificate file (apache.crt) and private key file (apache.key) to the C:\Apache24\conf folder.

2. Edit the Apache SSL configuration file (C:/Apache24/conf/httpd.conf), and add the following lines or uncomment if already present.

The below lines enable the SSL module and allow Apache to work on HTTPS Port.

LoadModule ssl_module modules/mod_ssl.so
Include conf/extra/httpd-ssl.conf
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so

3. Now, edit the Apache SSL file (C:/Apache24/conf/extra/httpd-ssl.conf) and add the following lines. This file will be called by httpd.conf file internally as defined in the httpd.conf file (Include conf/extra/httpd-ssl.conf).

SSLCertificateFile "C:\Apache24\conf\apache.crt"
SSLCertificateKeyFile "C:\Apache24\conf\apache.key"

4. Run the following commands on PowerShell to navigate to the Apache installation bin folder, and start the Apache service.

# Change the working directory
cd C:\ProgramFiles\OpenSSL-Win64\bin
# Start the Apache service
./httpd.exe
Starting the Apache server on a Windows machine
Starting the Apache server on a Windows machine

5. Finally, navigate to https://localhost to verify the Apache server.

You should see the same (It works!) message on the page, which confirms the Apache server is running with a self-signed certificate on a Windows machine.

Verifying Apache on windows on Port HTTPS
Verifying Apache on windows on Port HTTPS

Conclusion

In this tutorial, you learned how to configure an Apache web server on both Ubuntu and Windows operating systems and verify that you can access an Apache instance securely.

Now, how do you plan to up your game with Apache? Perhaps automate web deployments? Or create a Jenkins CI CD pipeline to improve your software development process?

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:\LocalMachine\My

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:\LocalMachine\My" | Where-Object Thumbprint -eq 2175A76B10F843676951965F52A718F635FFA043 | Select-Object *

list self-signed certificate properties 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

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:\LocalMachine\My

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:\LocalMachine\My -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:\LocalMachine\My

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:\localmachine\my -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:\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 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:\ps\export-certname.cer
Import-Certificate -CertStoreLocation Cert:\LocalMachine\AuthRoot -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:\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 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:\CurrentUser\Root"

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:\LocalMachine\My" -Protocol https

  • Starcraft remastered не запускается на windows 10
  • Star wars темы для windows
  • Ssl network extender отключен и не может быть запущен windows 10
  • Start cpverify addreg file c windows system32 wininet dll
  • Start pxe over ipv6 что это такое windows