Оснастка сертификаты windows 10 команда

Manage Certs with Windows Certificate Manager and PowerShellДанный материал является переводом оригинальной статьи «ATA Learning : Michael Soule : Manage Certs with Windows Certificate Manager and PowerShell».

Работа с сертификатами обычно является одной из тех дополнительных задач, которые вынужден брать на себя системный администратор Windows. Диспетчер Сертификатов Windows (Windows Certificate Manager) — это один из основных инструментов, который позволяет выполнять эту работу.

В этой статье мы рассмотрим работу с сертификатами применительно к операционной системе Windows. Если же вы хотите узнать больше о том, как работают сертификаты в целом, ознакомьтесь с сопутствующей статьей «Your Guide to X509 Certificates».

Понимание хранилищ сертификатов

В диспетчере сертификатов Windows все сертификаты находятся в логических хранилищах, называемых «хранилищами сертификатов». Хранилища сертификатов – это «корзины», в которых Windows хранит все сертификаты, которые в настоящее время установлены, и сертификат может находиться более чем в одном хранилище.

К сожалению, хранилища сертификатов — не самая интуитивно понятная концепция для работы. О том, как различать эти хранилища и как с ними работать, вы прочитаете ниже.

Каждое хранилище находится в Реестре Windows и в файловой системе. При работе с сертификатом в хранилище вы взаимодействуете с логическим хранилищем, не изменяя напрямую реестр или файловую систему. Этот более простой способ позволяет вам работать с одним объектом, в то время как Windows заботится о том, как представить этот объект на диске.

Иногда можно встретить хранилища сертификатов, называемые физическими или логическими хранилищами. Физические хранилища ссылаются на фактическую файловую систему или место в реестре, где хранятся разделы реестра и / или файл(ы). Логические хранилища — это динамические ссылки, которые ссылаются на одно или несколько физических хранилищ. С логическими хранилищами намного проще работать, чем с физическими хранилищами для наиболее распространенных случаев использования.

Windows хранит сертификаты в двух разных областях — в контексте пользователя и компьютера. Сертификат помещается в один из этих двух контекстов в зависимости от того, должен ли сертификат использоваться одним пользователем, несколькими пользователями или самим компьютером. В остальной части этой статьи сертификат в контексте пользователя и компьютера будет неофициально называться сертификатами пользователей и сертификатами компьютеров.

Сертификаты пользователей

Если вы хотите, чтобы сертификат использовался одним пользователем, то идеальным вариантом будет хранилище пользовательских сертификатов внутри Диспетчера сертификатов Windows. Это общий вариант использования процессов аутентификации на основе сертификатов, таких как проводной IEEE 802.1x.

Сертификаты пользователей находятся в профиле текущего пользователя и логически отображаются только в контексте этого пользователя. Сертификаты пользователей «сопоставлены» и уникальны для каждого пользователя даже в одних и тех же системах.

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

Если сертификат будет использоваться всеми пользователями компьютера или каким-либо системным процессом, его следует поместить в хранилище в контексте компьютера. Например, если сертификат будет использоваться на веб-сервере для шифрования связи для всех клиентов, размещение сертификата в контексте компьютера будет подходящим вариантом.

Вы увидите, что хранилище сертификатов компьютера логически сопоставлено для всех пользовательских контекстов. Это позволяет всем пользователям использовать сертификаты в хранилище сертификатов компьютера в зависимости от разрешений, настроенных для закрытого ключа.

Сертификаты компьютера находятся в кусте реестра локального компьютера и в подкаталогах \ProgramData. Сертификаты пользователя находятся в кусте реестра текущего пользователя и в подкаталогах \AppData. Ниже вы можете увидеть, где каждый тип хранилища находится в реестре и файловой системе.

Контекст Путь реестра Объяснение
User HKEY_CURRENT_USER
SOFTWARE\Microsoft\SystemCertificates\
Физическое хранилище для пользовательских открытых ключей
User HKEY_CURRENT_USER
SOFTWARE\Policies\Microsoft\SystemCertificates\
Физическое хранилище для пользовательских открытых ключей, установленных объектами групповой политики Active Directory (AD) (GPO)
Computer HKEY_LOCAL_MACHINE
SOFTWARE\Microsoft\SystemCertificates\
Физическое хранилище общедоступных ключей для всей машины
Computer HKEY_LOCAL_MACHINE
SOFTWARE\Microsoft\Cryptography\Services\
Физическое хранилище ключей, связанных с определенной службой
Computer HKEY_LOCAL_MACHINE
SOFTWARE\Policies\Microsoft\SystemCertificates\
Физическое хранилище открытых ключей для всей машины, установленных объектами групповой политики.
Computer HKEY_LOCAL_MACHINE
SOFTWARE\Microsoft\EnterpriseCertificates\
Физическое хранилище общедоступных ключей, установленных корпоративными контейнерами PKI в домене AD
Контекст Расположение файла Объяснение
User $env:APPDATA\Microsoft\SystemCertificates\ Физическое хранилище для пользовательских открытых ключей и указателей на закрытые ключи
User $env:APPDATA\Microsoft\Crypto\ Физическое хранилище для контейнеров закрытых ключей для конкретных пользователей
Computer $env:ProgramData\Microsoft\Crypto\ Физическое хранилище для контейнеров закрытых ключей для всей машины
Предварительные требования

В оставшейся части этой статьи вы найдете несколько примеров, демонстрирующих взаимодействие с хранилищами сертификатов Windows. Чтобы воспроизвести эти примеры, убедитесь, что выполняются следующие требования:

  • Windows Vista, Windows Server 2008 или более новая операционная система. В показанных примерах используется Windows 10 Корпоративная версии 1903.
  • Знакомство с PowerShell. Хотя это и не обязательно, этот язык будет использоваться для ссылки на сертификаты, где это необходимо. Все показанные примеры были созданы с помощью Windows PowerShell 5.1.
  • Вам не потребуется устанавливать какие-либо специальные сертификаты, но использование самозаверяющего сертификата полезно.
Управление сертификатами в Windows

В Windows есть три основных способа управления сертификатами:

  • Оснастка консоли управления Microsoft (MMC) сертификатов (certmgr.msc)
  • PowerShell
  • Инструмент командной строки certutil

В этой статье вы узнаете, как управлять сертификатами с помощью оснастки Certificates MMC и PowerShell. Если вы хотите узнать больше о том, как использовать certutil, ознакомьтесь с документацией Microsoft.

PowerShell против диспетчера сертификатов Windows

Поскольку в Windows можно управлять сертификатами несколькими способами, встаёт вопрос выбора, что лучше использовать — GUI (MMC) или командную строку с PowerShell.

Во-первых, рассмотрим жизненный цикл сертификата. Если вы собираетесь установить или удалить один сертификат только один раз, рассмотрите возможность использования MMC. Но если вы управляете несколькими сертификатами или выполняете одну и ту же задачу снова и снова, использование командной строки может оказаться правильным решением. Даже если вы не умеете писать сценарии PowerShell, вам стоит этому научиться, если у вас есть много разных сертификатов, которыми нужно управлять.

Давайте сначала посмотрим, как обнаружить сертификаты, установленные в Windows, с помощью диспетчера сертификатов и PowerShell.

Использование диспетчера сертификатов Windows (certmgr.msc)

Чтобы просмотреть сертификаты с помощью MMC, откройте Диспетчер сертификатов: откройте меню «Пуск» и введите certmgr.msc. Это вызовет Windows Certificates MMC. Это начальное представление предоставит обзор всех логических хранилищ, отображаемых в левом окне.

На снимке экрана ниже видно, что выбрано логическое хранилище доверенных корневых центров сертификации

Windows Trusted Root Certification Authorities store

Просмотр физических хранилищ

По умолчанию Диспетчер сертификатов Windows не отображает физические хранилища. Чтобы показать их, в верхнем меню оснастки выбирайте «View» > «Options«. Затем вы увидите варианты отображения физических хранилищ сертификатов. Включение этого параметра упрощает определение конкретных путей в Windows.

 The Certificates MMC View Options with Physical certificate stores selected.

Теперь вы можете видеть, что дополнительные контейнеры показаны в примере логического хранилища доверенных корневых центров сертификации, показанном ранее. Сертификаты по-прежнему сгруппированы относительно их логических хранилищ, но теперь вы можете увидеть физическое хранилище «Реестр».

Inspecting the physical cert stores

Проверка атрибутов в диспетчере сертификатов Windows

Есть много атрибутов сертификата, которые вы можете увидеть при просмотре их с помощью MMC. Например, вы, вероятно, захотите выбрать определенные сертификаты по их атрибутам. Самый простой способ сделать это — указать Serial Number сертификата или значение Thumbprint. Если сертификат был подписан центром сертификации (CA), при выдаче он будет иметь серийный номер. Thumbprint вычисляется каждый раз при просмотре сертификата.

Вы можете увидеть некоторые атрибуты сертификата, открыв его в MMC, как показано ниже.

Inspecting a Windows certificate

Следует отметить одну важную особенность — встроенные закрытые ключи. Сертификаты в Windows также могут иметь соответствующий закрытый ключ. Эти закрытые ключи хранятся в соответствующих физических хранилищах в виде зашифрованных файлов.

Чтобы быстро отличать сертификаты с соответствующим закрытым ключом и без него, посмотрите на значок сертификата. В Диспетчере сертификатов Windows, если значок просто выглядит как лист бумаги с лентой, соответствующий закрытый ключ отсутствует. Если у сертификата есть закрытый ключ, вы увидите ключ на значке MMC, и ключ в нижней части вкладки «Общие» при открытии сертификата

Certificate without an embedded private key (Сертификат без встроенного закрытого ключа)

Использование PowerShell по физическому хранилищу

Как и в случае с MMC, вы можете просматривать сертификаты и управлять ими с помощью PowerShell. Давайте сначала проверим сертификаты в их физических хранилищах (реестр и файловая система).

Используя PowerShell командлет Get-ChildItem, вы можете перечислить все ключи и значения внутри родительского пути в реестре. Приведенная ниже команда перечислит все сертификаты вошедшего в систему пользователя в логическом хранилище промежуточных центров сертификации.

Get-ChildItem -Path 'HKCU:\Software\Microsoft\SystemCertificates\CA\Certificates'

Каждая запись в кусте реестра, который вы видите, будет соответствовать отпечатку сертификата доверенного центра сертификации и его сертификату в соответствующем свойстве. Вы можете увидеть пример вывода ниже.

Results of the installed certificates from the example commands

Другое распространенное хранилище — это Personal store. Ваши сертификаты для этого хранилища находятся в файловой системе, а не в реестре. В следующих командах мы покажем эти различные физические пути и их цели.

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

Get-ChildItem -Path $env:APPDATA\Microsoft\SystemCertificates\My\Certificates\

Каждый файл, возвращаемый в приведенной ниже команде, является ссылкой на объект для закрытого ключа, созданный поставщиком хранилища ключей (KSP). Имя файла соответствует идентификатору ключа субъекта сертификата. К каждому устанавливаемому вами закрытому ключу будет добавлен соответствующий файл.

Get-ChildItem -Path $env:APPDATA\Microsoft\SystemCertificates\My\Keys\

Каждый файл в каталоге, возвращаемый следующей командой, является уникальным контейнером для зашифрованного закрытого ключа, созданного KSP. Нет прямой связи между именем файла и сертификатом, но файл является целью указателя в предыдущей команде.

Get-ChildItem -Path $env:APPDATA\Microsoft\Crypto\Keys
Использование PowerShell по логическому хранилищу

Поскольку работа с сертификатами на их физических путях встречается редко, в остальных примерах вы будете работать с логическими хранилищами.

PowerShell может получить доступ к логическим хранилищам Windows с помощью PSDrive-объекта «Cert:\«, который сопоставляет сертификаты с физическими хранилищами так же, как это делает MMC.

К сожалению, MMC и «Cert:» не маркируют логические хранилища одинаково. Ниже вы можете увидеть сравнительную таблицу общих хранилищ и их названий как в MMC, так и в «Cert:» PSDrive.

Cert: Certificates MMC
My Personal
Remote Desktop Remote Desktop
Root Trusted Root Certification Authorities
CA Intermediate Certification Authorities
AuthRoot Third-Party Root Certification Authorities
TrustedPublisher Trusted Publishers
Trust Enterprise Trust
UserDS Active Directory User Object
Выбор сертификатов

Когда вы работаете с сертификатами, вам понадобится способ фильтрации и выбора сертификатов для выполнения определенных операций. В большинстве случаев вы будете фильтровать и выбирать сертификаты на основе значения определенного расширения.

Для следующих примеров вам нужно начать с перечисления всех установленных сертификатов в хранилище корневого ЦС.

Get-ChildItem -Path 'Cert:\CurrentUser\Root\'

Возвращенные объекты будут объектами сертификатов, которые вы можете использовать в следующих примерах.

Общие расширения уже доступны как свойства объектов сертификата. В приведенном ниже примере вы используете Get-Member для вывода списка всех свойств возвращаемых объектов.

Get-ChildItem -Path 'Cert:\CurrentUser\Root\' | Get-Member -MemberType Properties

The properties available for the returned certificate objects

Как видим, некоторые из этих расширений, например «Issuer», помогают найти сертификат, который вы ищете. Расширения предоставляют информацию о сертификате, например, кому он выдан, для чего его можно использовать и любые ограничения на него.

В более сложных случаях использования вам может понадобиться найти сертификаты других расширений, таких как используемый шаблон сертификата. Сложность в том, что значения этих расширений возвращаются как массив целых чисел. Эти целые числа соответствуют содержимому в кодировке ASN.1.

Покажем пример взаимодействия с свойствами типа ScriptProperty. В приведенной ниже команде вы извлекаете Key Usages.

((Get-ChildItem -Path 'Cert:\CurrentUser\Root\' | Select -First 1).Extensions | Where-Object {$_.Oid.FriendlyName -eq 'Key Usage'}).format($true)

Новая часть, которую мы вводим в приведенной выше команде, — это метод форматирования, который выполняет декодирование ASN.1. Вы передаете ему логическое значение (например, $true), чтобы определить, хотим ли мы, чтобы возвращаемый объект был однострочным или многострочным.

Попробуем использовать значение Thumbprint из сертификата в приведенной ниже команде. Значение Thumbprint устанавливается как переменная PowerShell и используется для выбора конкретного сертификата в приведенных ниже командах.

$thumb = "cdd4eeae6000ac7f40c3802c171e30148030c072"
Get-ChildItem -Path 'Cert:\CurrentUser\Root\' | Where-Object {$_.Thumbprint -eq $thumb}
Создание самозаверяющих (self-signed) сертификатов с помощью PowerShell

PowerShell может создавать самозаверяющие (self-signed) сертификаты с помощью командлета New-SelfSignedCertificate. Самозаверяющие сертификаты полезны для тестирования, поскольку они позволяют генерировать пару открытого и закрытого ключей без использования центра сертификации.

Теперь давайте создадим самозаверяющий сертификат в хранилищах текущего пользователя и локального компьютера, чтобы использовать его в примерах для следующих шагов.

В приведенном ниже примере PowerShell создает пару открытого и закрытого ключей, самозаверяющий сертификат и устанавливает их все в соответствующие хранилища сертификатов.

New-SelfSignedCertificate -Subject 'User-Test' -CertStoreLocation 'Cert:\CurrentUser\My'
New-SelfSignedCertificate -Subject 'Computer-Test' -CertStoreLocation 'Cert:\LocalMachine\My'

Использование самозаверяющих сертификатов для продуктивных сервисов не рекомендуется, поскольку не существует всех механизмов, основанных на доверии.

Импорт и экспорт сертификатов в MMC

Криптография с открытым ключом основана на широкой доступности открытого ключа. Учитывая это, вам нужны стандартные способы эффективного обмена сертификатами. Не менее важна безопасность ваших личных ключей. Хранение закрытых ключей на недоступных носителях или с материалами для аварийного восстановления — обычная практика для определенных закрытых ключей.

Оба они требуют способов хранения этих криптографических объектов в стандартных форматах. Экспорт предоставляет функции для сохранения этих объектов и обеспечения использования широко распространенных стандартных форматов файлов. Импорт позволяет вам переносить криптографические объекты в операционные системы Windows.

Экспорт сертификатов из MMC относительно прост. Чтобы экспортировать сертификат без закрытого ключа, щелкните сертификат в MMC, выберите меню «Все задачи», а затем «Экспорт».

Во время экспорта вам будет предложено указать формат файла, как показано ниже. Наиболее распространены варианты кодирования — DER или Base-64

Exporting a certificate with no private key or one that is marked as not exportable

Экспорт закрытых ключей

Чтобы экспортировать сертификат с соответствующим закрытым ключом, вы должны соответствовать двум критериям:

  • Вошедшая в систему учетная запись должна иметь разрешение на закрытый ключ (только для сертификатов компьютеров);
  • Закрытый ключ должен быть помечен как экспортируемый.

Чтобы проверить разрешения для закрытых ключей локального компьютера, вы можете выбрать сертификат с закрытым ключом, выбрать «Все задачи» и «Управление закрытыми ключами» в MMC «Сертификаты». В открывшемся диалоговом окне отображаются записи управления доступом для закрытых ключей.

he Basic Security Property Page for the private keys of a certificate with the Subject of ServerName

Когда выше обозначенные условия выполнены, вы можете выбрать сертификат, щелкнуть «Все задачи», а затем «Экспорт», как если бы вы использовали сертификат только с открытым ключом. При экспорте теперь у вас должна присутствовать возможность выбора экспорта закрытого ключа («Yes, export the private key»), как показано ниже.

Certificate Export Wizard with exportable private key

Когда вы экспортируете закрытый ключ в Windows, вы можете сохранить файл только как PFX. Этот и другие типы файлов и форматы кодирования подробно описаны в этом посте.

Для остальных параметров, отображаемых в мастере экспорта, вы можете использовать значения по умолчанию. В таблице ниже приводится краткое изложение каждого из них.

Настройка Описание
Including all certificates in the certification path if possible Помогает с переносимостью эмитентов сертификатов и включает все соответствующие открытые ключи в PFX.
Delete the private key if the export is successful Удаляет закрытый ключ из файла и имеет несколько распространенных вариантов использования, но одним из примеров является проверка доступа к закрытым ключам.
Export all extended properties Будет включать любые расширения в текущем сертификате, они относятся к сертификатам [конкретные настройки] для интерфейсов Windows.
Enable certificate privacy Обычно в экспортируемом PFX-файле шифруется только закрытый ключ, этот параметр шифрует все содержимое PFX-файла.
Group or user names Вы можете использовать участника безопасности группы или пользователя из Active Directory для шифрования содержимого файла PFX, но пароль является наиболее переносимым вариантом для устаревших систем или компьютеров, не присоединенных к тому же домену.
Импорт сертификатов

Функция импорта одинакова для всех поддерживаемых типов файлов сертификатов. Единственная разница в том, что если файл содержит закрытый ключ, вы можете «Отметить этот ключ как экспортируемый», о чем вы узнаете подробнее ниже. Windows будет использовать мастер импорта сертификатов.

Certificate Import Wizard with a PFX file

При использовании мастера импорта сертификатов для PFX вам потребуется указать пароль, используемый для шифрования закрытого ключа. Вот еще один обзор вариантов импорта.

Настройка Описание
Enable strong private key protection Требуется пароль для каждого доступа к закрытому ключу. Будьте осторожны с новыми функциями, поскольку они не будут поддерживаться во всех программах.
Mark this key as exportable Вы должны стараться избегать использования этого параметра в любой конечной системе, закрытые ключи следует рассматривать так же, как и хранение паролей.
Protect private key using [virtualization-based security] Этот параметр обеспечивает дополнительные функции безопасности для защиты закрытых ключей от сложных атак вредоносного ПО.
Include all extended properties Относится к тем же настройкам Windows, что и при экспорте.

Сертификаты для подписи кода PowerShell — хороший вариант использования надежной защиты закрытого ключа.

С автоматическим размещением сертификатов следует проявлять осторожность. Скорее всего, вы получите наилучшие результаты, выбрав хранилище сертификатов вручную.

Импорт и экспорт сертификатов в PowerShell

Теперь с помощью PowerShell экспортируйте один из самозаверяющих сертификатов, которые вы создали ранее. В этом примере вы выбираете сертификат в личном логическом хранилище CurrentUser, который был самозаверяющим.

$certificate = Get-Item (Get-ChildItem -Path 'Cert:\CurrentUser\My\' | Where-Object {$_.Subject -eq $_.Issuer}).PSPath

Теперь, когда вы выбрали сертификат, вы можете использовать команду Export-Certificate, чтобы сохранить файл в кодировке DER, используя команду ниже.

Export-Certificate -FilePath $env:USERPROFILE\Desktop\certificate.cer -Cert $certificate

Теперь давайте посмотрим на экспорт закрытого ключа. Ниже вы проверяете, что у выбранного сертификата есть закрытый ключ. Если он не возвращает True, то команда Get-Item, скорее всего, выбрала неправильный сертификат.

$certificate.HasPrivateKey

Ниже вы установите пароль, который будет использоваться для шифрования закрытого ключа. Затем экспортируйте выбранный сертификат в файл PFX и используйте пароль, который вы ввели ранее, чтобы зашифровать файл.

$pfxPassword = "ComplexPassword!" | ConvertTo-SecureString -AsPlainText -Force
Export-PfxCertificate -FilePath $env:USERPROFILE\Desktop\certificate.pfx -Password $pfxPassword -Cert $certificate

В случае, если необходимо выполнить импорт, как и при экспорте, есть две команды. Одна команда для импорта сертификатов и одна для импорта файлов PFX.

Ниже команда Import-Certificate импортирует файл в формате DER, который вы экспортировали ранее, в личное хранилище текущего пользователя.

Import-Certificate -FilePath $env:USERPROFILE\Desktop\certificate.cer -CertStoreLocation 'Cert:\CurrentUser\My'

Допустим, вы тоже хотите установить закрытый ключ этого сертификата.

$pfxPassword = "ComplexPassword!" | ConvertTo-SecureString -AsPlainText -Force
Import-PfxCertificate -Exportable -Password $pfxPassword -CertStoreLocation 'Cert:\CurrentUser\My' -FilePath $env:USERPROFILE\Desktop\certificate.pfx

Имейте в виду, что пароль должен быть защищенной строкой. Кроме того, если вы импортируете в хранилище локального компьютера (например, «Cert:\LocalMachine«), вам нужно будет запустить команду из командной строки администратора с повышенными привилегиями.

В приведенном выше примере вы также используете параметр -Exportable с командой, отмечая закрытый ключ как экспортируемый в будущем. По умолчанию (без указания этого параметра) экспорт не используется. Экспортируемые закрытые ключи – отельный аспект информационной безопасности, заслуживающий отдельного внимания.

Удаление сертификатов с помощью PowerShell

При удалении сертификатов помните, что понятие «Корзина Windows» в этом случае отсутствует. Как только вы удалите сертификат, он исчезнет! Это означает, что очень важно подтвердить, что вы удаляете правильный сертификат, путем проверки уникального идентификатора, такого как серийный номер или значение расширения Thumbprint.

Как и выше, в приведенной ниже команде мы выбираем самозаверяющий сертификат из личного хранилища текущего пользователя.

$certificate = Get-Item (Get-ChildItem -Path 'Cert:\CurrentUser\My\' | Where-Object {$_.Subject -eq $_.Issuer}).PSPath

Ниже вы можете увидеть свойства отпечатка, серийного номера и темы для выбранного сертификата, чтобы убедиться, что это именно тот сертификат, который вы собираетесь выбрать.

$certificate.Thumbprint
$certificate.SerialNumber
$certificate.Subject

Убедитесь, что вы выбрали правильный сертификат, который собираетесь удалить.

Приведенная ниже команда удаляет все выбранные объекты сертификата, используйте с осторожностью! Передав объект $certificate через конвейер в командлет Remove-Item в приведенной ниже команде, вы удалите все содержимое сертификата без каких-либо запросов на проверку.

$certificate | Remove-Item
Резюме

На протяжении всей этой статьи вы работали с сертификатами в Windows, изучая, как получить к ним доступ, и некоторые инструменты, которые можно использовать при работе с ними. По этой теме можно изучить гораздо больше, в том числе о том, как связать установленные сертификаты с конкретными службами или даже о том, как реализовать инфраструктуру закрытого открытого ключа (PKI) путем развертывания собственных центров сертификации (CA).

How to View Certificates on Windows 10 (Using Windows 10 Certificate Manager)

Home » How to View Certificates on Windows 10 (Using Windows 10 Certificate Manager)

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

This brief guide introduces you to Windows 10 Certificate Manager. This tool allows you to view and manage installed digital certificates on Windows devices as well as view CRLs and CTLs as well

When you install digital certificates onto your computer, there’s one place where they should be imported right away: the Windows 10 Certificate Manager. This tool is an easy-to-use console where you can view installed certificates on your Windows 10 device all in one place. This includes:

  • Code signing certificates
  • Client authentication certificates
  • Document signing certificates.

But the Windows 10 Certificate Manager doesn’t store only your personal or organizational certificates — it’s also where you can view:

  • All publicly trusted root certificates that are pre-installed on your device,
  • Certificate revocation lists (CRLs), and
  • Certificate trust lists (CTLs).

This article will familiarize you with the Windows 10 Certificate Manager tool that’s built into your machine. After that, we’ll walk you through the processes of how to view both organizational and publicly trusted digital certificates that are installed on your device.

What Is the Windows 10 Certificate Manager? It’s How You Can View Installed Certificates

The Certificate Manager is a console that comes installed on every modern Windows computer. It’s a tool that enables you to do many things relating to digital certificates that are installed on your device, including:

  • View installed certificates,
  • Modify your certificates,
  • Export existing certificates,
  • Delete existing certificates, and
  • Import new certificates.

This is also where you can view your device’s trust store for publicly trusted certificates (i.e., certificates issued by trusted certificate authorities [CAs]) that come pre-installed on your device. More on that toward the end of the article. But first, there’s one other important thing to mention before we move on to how to view certificates in Windows 10.

There are Two Types of Window Certificate Manager Tools (Snap-In vs Command-Line Utility)

Certmgr.msc is a Microsoft Management Console (MMC) snap-in. The snap-in is a handy interface where you can add specific tools to your device’s admin console (e.g., a certificate manager). This differs from the Certmgr.exe, which is a command-line utility certificate manager.

Now that we know what Windows Certificate Manager console is and why it’s useful, let’s get right to how you can use it to view, delete or install certificates onto your device.

How to View Installed Certificates on Windows 10 (Organizational & Individual Certificates)

1. First, open your Windows 10 Certificate Manager. You can do this by typing either Cert or Certificate in the run menu.

Manage User Certificates

2. Select the Manage user certificates option at the top of the menu. This will populate another window title Certmgr. This is the Certificate Manager tool, which allows you to view installed certificates on Windows 10.

3. In the left pane, double-click the Personal folder to display a sub-folder titled Certificates.

crtmrg window

4. Select the Certificates folder in the left navigation to view the list of digital certificates you have installed on your machine. These will display in the right pane.

csrmgt option

That’s it! Now, you can view any of these individual certificates by simply double-clicking on it. Doing this will open a new window that displays the digital certificate’s information, including:

  • The certificate’s intended uses,
  • Who it’s assigned to, and
  • What trusted certificates it stems from and whether it’s trustworthy.
certificate installed

Now you know how to view installed certificates on Windows 10! Of course, if you’re curious to know what certificates you have installed on your device through Windows, then keep reading.

trusted root certificate

This will display a folder labeled Certificates, which will display the trusted root certificates that are installed on your device:

list of certificates

That’s it! As you can see, understanding how to view certificates on Windows 10 isn’t complicated at all once you know what it is you’re looking for. There’s really nothing to it.

If you want to learn how to import or install a code signing certificate on Windows, check out our other guide.

Диспетчер сертификатов или Certmgr.msc в Windows позволяет просматривать сведения о ваших сертификатах, экспортировать, импортировать, изменять, удалять или запрашивать новые сертификаты. Корневые сертификаты – это цифровые документы, используемые для управления сетевой аутентификацией и обменом информацией.

Управление сертификатами с помощью диспетчера сертификатов или Certmgr.msc

Консоль диспетчера сертификатов является частью консоли управления Microsoft в Windows 10/8/7. MMC содержит различные инструменты, которые можно использовать для функций управления и обслуживания. Как упоминалось ранее, используя certmgr.msc, вы можете просматривать свои сертификаты, а также изменять, импортировать, экспортировать, удалять или запрашивать новые.

Для управления сертификатами в меню WinX в Windows выберите «Выполнить». Введите certmgr.msc в поле «Выполнить» и нажмите Enter. Помните, что вам нужно будет войти в систему как администратор. Диспетчер сертификатов откроется.

Вы увидите, что все сертификаты хранятся в разных папках в разделе Сертификаты – текущий пользователь . Когда вы откроете любую папку сертификатов, вы увидите, что сертификаты отображаются на правой панели. На правой панели вы увидите такие столбцы, как «Выдан», «Выдан», «Срок действия», «Назначение», «Понятное имя», «Статус» и «Шаблон сертификата». В столбце «Предполагаемые цели» указано, для чего используется каждый сертификат.

Используя диспетчер сертификатов, вы можете запросить новый сертификат с тем же ключом или другим ключом. Вы также можете экспортировать или импортировать сертификат. Чтобы выполнить какое-либо действие, выберите сертификат, щелкните меню «Действие»> «Все задачи», а затем щелкните нужную команду действия. Вы также можете щелкнуть правой кнопкой мыши контекстное меню, чтобы выполнить эти действия.

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

Следует отметить, что Certmgr.msc является оснасткой консоли управления Microsoft, тогда как Certmgr.exe является утилитой командной строки. Если вы хотите узнать о параметрах командной строки в certmgr.exe, вы можете посетить MSDN.

Прочтите это, если получите. Проблема с сертификатом безопасности этого веб-сайта в сообщении IE.

Download Windows Speedup Tool to fix errors and make PC run faster

The Certificate Manager or Certmgr.msc in Windows 11/10/8/7 lets you see details about your certificates, export, import, modify, delete or request new certificates. Root Certificates are digital documents used to manage network authentication and the exchange of information.

Manage certificates using Certificate Manager or Certmgr.msc

Windows Certificate Manager Certmgr.msc

The Certificates Manager Console is a part of the Microsoft Management Console in Windows 10/8/7.  The MMC contains various tools that can be used for managing and maintenance functions. As mentioned earlier, using certmgr.msc you can view your certificates as well as modify, import, export, delete or request new ones.

To manage your certificates, from the WinX Menu in Windows, select Run. Type certmgr.msc in the Run box and hit Enter. Remember, you will have to be logged on as an administrator. The Certificate Manager will open.

You will see that all the Certificates are stored in various folders under Certificates – Current User. When you open any certificates folder, you will see that the certificates are displayed in the right pane. In the right pane, you will see columns like Issued To, Issued By, Expiration date, Intended Purpose, Friendly Name, Status and Certificate Template. The Intended Purposes column tells you what each certificate is used for.

Using the Certificate Manager, you can request a new certificate with the same key or a different key. You can also export or import a certificate. To carry out any action, select the certificate, click the Action menu > All Tasks, and then click the required action command. You can also right-click on the context menu to carry out these actions.

Related: Fix Wi-Fi Certificate Error on Windows 11/10

In case you wish to export or import certificates, an easy-to-follow wizard will open which will take you through the required steps.

export windows certificates

It is to be noted that Certmgr.msc is a Microsoft Management Console snap-in whereas Certmgr.exe is a command-line utility. If you want to learn about the command-line options in certmgr.exe you can visit MSDN.

Read this if you receive There is a problem with this website’s security certificate in IE message.

Anand Khanse is the Admin of TheWindowsClub.com, a 10-year Microsoft MVP (2006-16) & a Windows Insider MVP (2016-2022). Please read the entire post & the comments first, create a System Restore Point before making any changes to your system & be careful about any 3rd-party offers while installing freeware.

If you’re a Windows system administrator, you might have been forced to work with windows certificates. Working with certificates in Windows is typically one of those extra hats a sysadmin has to take on. Using the Windows certificate manager as a tool, you can do it!

Certificates are notoriously complex and hard to understand but in this article, you’ll get a chance to discover certificates aren’t that scary in Windows!

This article will cover mainly working with certificates in Windows. If you’d like to learn more about how certificates work in general, check out this article’s companion X.509 Certificate Tutorial article.

Understanding Certificate Stores

Within the Windows certificate manager, all certificates exist in logical storage locations referred to as certificate stores. Certificate stores are “buckets” where Windows keeps all certificates that are currently installed and a certificate can be in more than one store.

Unfortunately, certificate stores are not the most intuitive concept with which to work. You will read about how to differentiate these stores and how to work with them below.

Each store is located in the Windows Registry and on the file system. Refer to the below table for details. When working with a certificate in a store, you are interfacing with the logical store; not directly modifying the registry or file system. This simpler manner lets you work with a single object while Windows takes care of how to represent that object on disk.

You’ll sometimes see certificate stores referred to as physical or logical stores. Physical stores reference the actual file system or registry location where the registry key(s) and/or file(s) are stored. Logical stores are dynamic references that reference one or more physical stores. Logical stores are much easier to work with than physical stores for most common use cases.

Windows stores certificates in two different areas – a user and computer context. A certificate is placed in one of these two contexts depending on if the certificate should be used by a single user, multiple users, or the computer itself. For the rest of this article, a certificate in a user and computer context will be informally called user certificates and computer certificates.

User Certificates

If you intend for a certificate to be used by a single user, then a user certificate store inside the Windows certificate manager is ideal. This is the common use case for certificate-based authentication processes such as wired IEEE 802.1x.

User certificates are located within the current user’s profile and are only logically mapped within that user’s context. User certificates are “mapped” and are unique for each user, even on the same systems.

Computer Certificates

If a certificate will be used by all users on a computer or a system process, it should be placed inside of a store in the computer context. For example, if a certificate will be used on a web server to encrypt communication for all clients, placing a certificate in a store in the computer context would be ideal.

You’ll see that a computer’s certificate store is logically mapped for all user contexts. This allows for certificates in a computer certificate store to be used by all users, depending on the permissions configured for the private key.

For more information on private keys, be sure to check out the article X.509 Certificates Tutorial: A Sysadmin Guide.

Computer certificates are located in the Local Machine Registry hives and the Program Data folder. User certificates are located in the Current User Registry hives and the App Data folder. Below you can see a breakdown of where each type of store is located in the registry and file system.

Context Registry Path Explanation
User HKCU:\SOFTWARE\Microsoft\SystemCertificates\ Physical store for user-specific public keys
User HKCU:\SOFTWARE\Policies\Microsoft\SystemCertificates\ Physical store for user-specific public keys installed by Active Directory (AD) Group Policy Objects (GPOs)
Computer HKLM:\SOFTWARE\Microsoft\SystemCertificates\ Physical store for machine-wide public keys
Computer HKLM:\SOFTWARE\Microsoft\Cryptography\Services\ Physical store for keys associated with a specific service
Computer HKLM:\SOFTWARE\Policies\Microsoft\SystemCertificates\ Physical store for machine-wide public keys installed by GPOs
Computer HKLM:\SOFTWARE\Microsoft\EnterpriseCertificates\ Physical store for machine-wide public keys installed by the Enterprise PKI Containers within an AD domain
Context File Location Explanation
User $env:APPDATA\Microsoft\SystemCertificates\ Physical store for user-specific public keys and pointers to private keys
User $env:APPDATA\Microsoft\Crypto\ Physical store for user-specific private key containers
Computer $env:ProgramData\Microsoft\Crypto\ Physical store for machine-wide private key containers

Prerequisites

Throughout the rest of this article, you will find multiple examples showing interactions with Windows certificate stores. To replicate these examples, be sure you meet the following prerequisites:

  • Windows Vista, Windows Server 2008, or newer operating system. The examples shown use Windows 10 Enterprise version 1903.
  • Familiarity with PowerShell. Although not required, this will be the language used to reference certificates where appropriate. The examples shown have all been created with Windows PowerShell 5.1.
  • You will not need any specific certificates installed to follow along, but using a self-signed certificate is beneficial.

Managing Certificates in Windows

In Windows, there are three primary ways to manage certificates:

  • The Certificates Microsoft Management Console (MMC) snap-in (certmgr.msc)
  • PowerShell
  • The certutil command-line tool

In this article, you’ll learn how to manage certificates via the Certificates MMC snap-in and PowerShell. If you’d like to learn more about how to use certutil, check out the Microsoft Docs.

PowerShell vs. the Windows Security Certificate Manager

Since certificates can be managed a few different ways in Windows, which one do you choose? Should you go the GUI (MMC) route or command-line with PowerShell?

Note: This article is relevant both for the Windows 7 Certificate Manager and Windows 10 Certificate Manager MMC snap-ins.

First, consider the lifecycle of a certificate. If you only intend to install or remove a single certificate once, consider using the MMC. But if you’re managing multiple certificates or find yourself performing the same task over and over again, the command-line route may be the way to go. Even if you don’t know how to write PowerShell scripts, it’d be worth learning if you have many different certificates to manage.

Let’s first take a look at how to discover the certificates installed on Windows using both the Certificate Manager and PowerShell.

Using the Windows Certificate Manager (certmgr.msc)

To view certificates with the MMC, open up the Certificate Manager open your Start menu and type certmgr.msc. This will bring up the Windows Certificates MMC. This initial view will provide an overview of all the logical stores displayed in the left window.

You can see in the screenshot below the Trusted Root Certification Authorities logical store is selected.

Trusted Root Certification Authorities store
Trusted Root Certification Authorities store

Viewing Physical Stores

By default, the Windows certificate manager will not show the actual physical stores. To show the stores, click on View and then on Options. You will then see options to choose to show physical certificate stores. Enabling this option makes identifying the specific paths within Windows easier.

Figure 2 - The Certificates MMC View Options with Physical certificate stores selected.
Figure 2 – The Certificates MMC View Options with Physical certificate stores selected.

You can now see additional containers are shown under the example Trusted Root Certification Authorities logical store shown previously.  The certificates are still grouped relative to their logical stores, but you can now see the physical store, “Registry”.

Inspecting the physical cert stores
Inspecting the physical cert stores

Inspecting Attributes in the Windows Certificate Manager

There are many attributes of a certificate you can see when viewing them with the MMC. For example, you will likely want to select specific certificates.

The easiest way for you to accomplish this is by referencing the certificate’s Serial Number or Thumbprint extension value. If the certificate was signed by a certificate authority (CA), it will have a serial number when issued. The Thumbprint is calculated every time the certificate is viewed.

You can see some of the attributes for a certificate by opening it up in the MMC as you can see below.

Inspecting a Windows certificate
Inspecting a Windows certificate

One important feature to point out is embedded private keys. Certificates in Windows can also have a corresponding private key. These private keys are stored in corresponding physical stores as encrypted files.

To quickly distinguish a certificate with and without a corresponding private key, look at the certificate icon. In the Windows certificate manager, if the icon simply looks like a piece of paper with a ribbon, there is no corresponding private key. If a certificate does have a private key, you will see a key in the MMC icon, and you will see a key at the bottom of the General tab when you open the certificate.

Certificate without an embedded private key
Certificate without an embedded private key

Using PowerShell

As with the MMC, you can view and manage certificates with PowerShell as well. Let’s first inspect certificates in their physical stores (the registry and file system).

By Physical Store

Using the Get-ChildItem PowerShell cmdlet, you can enumerate all of the keys and values inside of the parent HKCU:\Software\Microsoft\SystemCertificates\CA\Certificates\ registry key path.

The below command will enumerate all of the currently-logged-in user’s certificates in the Intermediate Certification Authorities logical store.

Get-ChildItem -Path HKCU:\Software\Microsoft\SystemCertificates\CA\Certificates\

Each entry in the Registry hive you see will correspond to the Thumbprint of the certificate for a trusted CA and it’s certificate in the corresponding property. You can see an example output of this below.

Results of the installed certificates from the example commands, limited to the first 5 entries.
Results of the installed certificates from the example commands, limited to the first 5 entries.

Another common store is, the Personal store. Your certificates for this store are located on the file system rather than the Registry. In the following commands we will show these different physical paths and their purposes.

Each file in the directory, returned by the command below, corresponds to a certificate installed in the Personal current user store.

Get-ChildItem -Path $env:APPDATA\Microsoft\SystemCertificates\My\Certificates\

Each file returned in the below command is a reference to the object for a private key created by the Key Storage Provider (KSP). The file name corresponds to the Subject Key Identifier of the certificate. Each private key you install will have a corresponding file added.

Get-ChildItem -Path $env:APPDATA\Microsoft\SystemCertificates\My\Keys\

Each file in the directory returned by the below command is the unique container for the encrypted private key created by the KSP. There is no direct relationship between the file name and the certificate, but the file is the target of the pointer in the earlier command.

Get-ChildItem -Path $env:APPDATA\Microsoft\Crypto\Keys

By Logical Store

Since working with certificates in their physical paths is uncommon, you will be working with the logical stores for the rest of the examples.

PowerShell can access Windows logical stores using the Cert: PSDrive. The Cert: PSDrive maps certificates to the physical stores much like the MMC does.

Unfortunately, the MMC and the Cert PSDrive do not label the logical stores the same. Below you can see a comparison table of the common stores and their names both in the MMC and the Cert PSDrive.

Cert: Certificates MMC
My Personal
Remote Desktop Remote Desktop
Root Trusted Root Certification Authorities
CA Intermediate Certification Authorities
AuthRoot Third-Party Root Certification Authorities
TrustedPublisher Trusted Publishers
Trust Enterprise Trust
UserDS Active Directory User Object
Selecting Certificates

When you are working with certificates you will need a way to filter and select certificates to perform specific operations against. Most of the time you will filter and select certificates based on the value of a specific extension.

For the following examples you need to start by listing all installed certificates in the root CA store.

Get-ChildItem -Path Cert:\CurrentUser\Root\

The returned objects will be certificate objects you can use in the following examples.

Common extensions are already available as properties of the certificate objects. In the below example you are using Get-Member to list all the properties of the returned objects.

Get-ChildItem -Path Cert:\CurrentUser\Root\ | Get-Member -MemberType Properties
Figure 9 - The properties available for the returned certificate objects.
Figure 9 – The properties available for the returned certificate objects.

As you can see in Figure 9, some of these extensions, like Issuer, are helpful for finding the certificate you are looking for. Extensions supply information about the certificate, such as who it is issued to, what it can be used for, and any restrictions on it.

In more complex use cases you will want to find certificates by other extensions, like the certificate template used. The difficulty is the values for these extensions return as an array of integers. These integers correspond to ASN.1 encoded content.

The existing ScriptProperties available on the object show examples for interfacing with these. In the below command you will pull the Key Usages manually to see this relationship.

((Get-ChildItem -Path Cert:\CurrentUser\Root\ | select -First 1).Extensions | Where-Object {$_.Oid.FriendlyName -eq "Key Usage"}).format($true)

The new piece we introduce in the above command is the format method, which performs the ASN.1 decoding. You pass it a boolean value (e.g. $true) above to identify whether we want the returned object to be single-line or multi-line.

You will use the Thumbprint value from the certificate in Figure 7 in the below command. The Thumbprint value is set as a PowerShell variable and used to select the specific certificate in the below commands.

$thumb = "cdd4eeae6000ac7f40c3802c171e30148030c072"
Get-ChildItem -Path Cert:\CurrentUser\Root\ | Where-Object {$_.Thumbprint -eq $thumb}

Creating Self-Signed Certificates with PowerShell

PowerShell can create self-signed certificates using the New-SelfSignedCertificate cmdlet. Self-signed certificates are useful for testing as they allow you to generate a public and private key pair without the use of a CA.

Let’s now create a self-signed certificate in the Current User and the Local Machine stores to use in examples for the next steps.

In the example below, PowerShell is generating a public and private key pair, a self-signed certificate, and installing them all into the appropriate certificate stores.

PS51> New-SelfSignedCertificate -Subject 'User-Test' -CertStoreLocation 'Cert:\CurrentUser\My'
PS51> New-SelfSignedCertificate -Subject 'Computer-Test' -CertStoreLocation 'Cert:\LocalMachine\My'

Using self-signed certificates for production services is not encouraged as all the trust-based mechanisms do not exist.

Importing/Exporting Certificates

Public key cryptography is fundamentally based on the public key being widely accessible. Given this tenement you need standard ways to effectively share certificates. Equally as important is security of your private keys. Storing private keys in inaccessible media, or with disaster recovery materials is a common practice for certain private keys.

Both of these require ways to store these cryptographic objects in standard formats. Exporting provides the functions to perform storing of these objects and ensure they use widely accepted standard file formats. Importing allows you to bring the cryptographic objects into Windows operating systems.

Using the Windows Certificate Manager (certmgr.msc)

Exporting certificates from the MMC is relatively straight forward. To export a certificate without a private key, click on the certificate in the MMC, click on the All Tasks menu and then on Export.

During the export, you will be asked for a file format as shown below. The most common options are DER or Base-64 encoded.

Exporting a certificate with no private key or one that is marked as not exportable.
Figure 10 – Exporting a certificate with no private key or one that is marked as not exportable.

Exporting Private Keys

To export a certificate with an associated private key, you’ll have to meet two criteria; the logged-in account must have permission to the private key (for computer certificates only) and the private key needs to be marked as exportable.

To verify the permissions for a local computer’s private keys, you can select a certificate with a private key, choose All Tasks, and Manage Private Keys from within the Certificates MMC. The dialog box that opens shows the access control entries for the private keys.

The Basic Security Property Page for the private keys of a certificate with the Subject of ServerName.
The Basic Security Property Page for the private keys of a certificate with the Subject of ServerName.

When those two or three prerequisites are met you can select a certificate, click on All Tasks and then on Export just like you would with a certificate with only a public key. When exported, you should now have option to select Yes, export the private key as shown below.

Certificate Export Wizard with exportable private key.
Certificate Export Wizard with exportable private key.

When you export a private key in Windows you can only save the file as a PFX. These file types and encoding formats are detailed at length in this post.

For the remaining settings shown in the export wizard, you can use the defaults. The below table is a quick rundown of each.

Setting Description
Including all certificates in the certification path if possible Helps with portability of certificate issuers, and includes all pertinent public keys in the PFX
Delete the private key if the export is successful Removes the private key from the file and has few common use cases, but one example is to test access to private keys
Export all extended properties Will include any extensions within the current certificate, these relate to the certificates [specific settings]() for Windows interfaces
Enable certificate privacy Normally only the private key will be encrypted in the exported PFX file, this setting encrypts the entire contents of the PFX file
Group or user names You can use a group or user security principal from Active Directory for encrypting the contents of the PFX file, but a password is the most portable option across legacy systems or computers not joined to the same domain

Importing Certificates

The import function is the same for all supported certificate file types. The only difference is if the file includes a private key you can “Mark this key as exportable”, which you will read more on below. Windows will leverage the Certificate Import Wizard.

Certificate Import Wizard with a PFX file.
Figure 12 – Certificate Import Wizard with a PFX file.

When you use the Certificate Import Wizard for a PFX you will need to supply the password used to encrypt the private key. Here is another recap of the import options.

Setting Description
Enable strong private key protection Requires a password for each access of a private key, be cautious of newer functions as they will not be supported in all software
Mark this key as exportable You should try to avoid using this setting on any end system, private keys should be treated similarly to storing passwords
Protect private key using [virtualization-based security] The setting provides more security functionality for protecting private keys from advanced malware attacks
Include all extended properties Relates to the same Windows-specific settings discussed as with exporting

PowerShell code signing certificates are a good use case for strong private key protection.

Automatic placement of certificates can be something of which to be cautious. You will likely have the best results manually selecting the certificate store.

Using PowerShell

Now, with PowerShell export one of the self-signed certificates you created earlier. In the example the Current User is used, but you can use either.

Below, you are selecting a certificate in the Current User Personal logical store that was self-signed, meaning where the issuer matches the subject.

$certificate = Get-Item (Get-ChildItem -Path Cert:\CurrentUser\My\ | Where-Object {$_.Subject -eq $_.Issuer}).PSPath

Now that you selected a certificate, you can use the Export-Certificate command to save a DER encoded file using the command below.

Export-Certificate -FilePath $env:USERPROFILE\Desktop\certificate.cer -Cert $certificate

Now lets look at exporting the private key as well. Below you are verifying that the certificate you selected has a private key, if this does not return true, then the Get-Item command likely selected the wrong certificate.

$certificate.HasPrivateKey

Below you will set a password to use for encrypting the private key. Then export the selected certificate into a PFX file and use the password you entered earlier to encrypt the file.

$pfxPassword = "ComplexPassword!" | ConvertTo-SecureString -AsPlainText -Force
Export-PfxCertificate -FilePath $env:USERPROFILE\Desktop\certificate.pfx -Password $pfxPassword -Cert $certificate

Similarly to exporting, there are two commands. One command for importing certificates and one for importing PFX files.

Below the Import-Certificate command imports the DER encoded file that you exported earlier to the Current User’s Personal store.

Import-Certificate -FilePath $env:USERPROFILE\Desktop\certificate.cer -CertStoreLocation Cert:\CurrentUser\My

Let’s say you want to install that certificate’s private key too.

$pfxPassword = "ComplexPassword!" | ConvertTo-SecureString -AsPlainText -Force
Import-PfxCertificate -Exportable -Password $pfxPassword -CertStoreLocation Cert:\CurrentUser\My -FilePath $env:USERPROFILE\Desktop\certificate.pfx

Keep in mind that the password needs to be a Secure String. As well, if you are importing to the Local Machine store (e.g. Cert:\LocalMachine\) you will need to run the command from an elevated Administrator prompt.

In the above example, you also use the Exportable parameter with the command, marking the private key as exportable in the future. The default is to not be exportable. Exportable private keys are another security consideration, and deserves further focus on how you secure them.

There are also many other things to do with certificates in Windows so you should explore more.

Removing Certificates with PowerShell

When removing certificates you need to keep in mind there is no Recycle Bin. Once you delete a certificate, it’s gone. This means it is critical to confirm you are deleting the correct certificate by validating a unique identifier, like the Serial Number or Thumbprint extension value.

Similarly to above, in the below command we select a self-signed certificate from the Current User’s Personal store.

$certificate = Get-Item (Get-ChildItem -Path Cert:\CurrentUser\My\ | Where-Object {$_.Subject -eq $_.Issuer}).PSPath

Below you can see the Thumbprint, Serial Number, and Subject properties for the selected certificate to ensure it is the certificate you intend to select.

$certificate.Thumbprint
$certificate.SerialNumber
$certificate.Subject

Verify you have selected the correct certificate you intend to delete.

The below command removes all selected certificate objects, please use with caution. By passing the $certificate object through the pipeline to the Remove-Item cmdlet in the below command, you will delete all certificate content without any validation prompts.

$certificate | Remove-Item

Summary

Throughout this article you have worked with certificates in Windows, learning how to access them and some tools to use when working with them. There is much more to explore on the topic, including how to associate installed certificates with specific services, or even how to implement a private Public Key Infrastructure (PKI) by deploying your own Certificate Authorities (CA).

Further Reading

  • Working with Certificates and IIS in Windows

  • Оснастка пользователи и компьютеры для windows 10
  • Оснастка для сертификатов windows 10
  • Оснастка для домена windows 10
  • Оснастка брандмауэр windows в режиме повышенной безопасности
  • Оснастка актив директори для windows 10