Computer >> Hướng Dẫn Máy Tính >  >> Hệ Thống >> Máy Chủ Windows

Cách tạo Self-Signed Certificate trong Windows với PowerShell

Đa số quản trị viên Windows, quen thuộc với PKI, biết về công cụ MakeCert.exe, cho phép tạo self-signed certificate. Công cụ này là một phần của Microsoft .NET Framework SDK và Microsoft Windows SDK. Trên các phiên bản Windows hiện đại (Windows 10/8.1 và Windows Server 2019/2016/2012R2), bạn có thể tạo self-signed certificate bằng cmdlet PowerShell tích hợp New-SelfSignedCertificate mà không cần công cụ bổ sung.

Sử dụng cmdlet New-SelfSignedCertificate PowerShell để tạo Self-Signed Certificate

Để tạo self-signed certificate với PowerShell, bạn có thể dùng cmdlet New-SelfSignedCertificate, là một phần của module PoSh PKI (Public Key Infrastructure):

Để liệt kê tất cả cmdlet có sẵn trong module PKI, chạy lệnh.

Get-Command -Module PKI

Cách tạo Self-Signed Certificate trong Windows với PowerShell

Khuyên dùng self-signed certificate cho mục đích test hoặc cung cấp certificate cho dịch vụ Intranet nội bộ (IIS, Exchange, Web Application Proxy, LDAPS, ADRMS, DirectAccess, v.v.) nếu bạn không thể triển khai hạ tầng PKI/CA hoặc mua certificate tin cậy từ nhà cung cấp bên ngoài.

Mẹo. Đừng quên bạn có thể dễ dàng lấy chứng chỉ SSL miễn phí từ Let's Encrypt. Đây là ví dụ cách cấp chứng chỉ Let's Encrypt SSL và gắn nó vào site IIS trên Windows Server.

Để tạo certificate, bạn phải chỉ định giá trị –DnsName (tên server, tên có thể tùy ý và khác tên localhost) và -CertStoreLocation (kho chứng chỉ cục bộ nơi certificate tạo sẽ được đặt). Bạn có thể dùng cmdlet để tạo self-signed certificate trên Windows 10 (trong ví dụ này), Windows 8.1 và Windows Server 2019/2016/2012 R2/2012.

Để tạo chứng chỉ SSL mới (kiểu SSLServerAuthentication mặc định) cho tên DNS test.contoso.com (dùng tên FQDN) và đặt nó vào danh sách chứng chỉ cá nhân trên máy tính, chạy lệnh sau:

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

Cách tạo Self-Signed Certificate trong Windows với PowerShell

Directory: Microsoft.PowerShell.Security\Certificate::LocalMachine\My
Thumbprint Subject
---------- -------
2175A76B10F843676951965F52A718F635FFA043 CN=test.contoso.com

Nếu bạn chạy lệnh này trong phiên PowerShell không nâng cao (không có quyền admin cục bộ), lỗi xuất hiện:

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

Nếu bạn chỉ định nhà cung cấp mật mã không tiêu chuẩn (CSP), ví dụ dùng tham số -KeyAlgorithm "ECDSA_secP256r1" -Provider "Microsoft Smart Card Key Storage Provider", hãy đảm bảo nó được cài trên máy tính (mặc định là Microsoft Enhanced Cryptographic Provider CSP). Nếu không, lỗi sẽ xuất hiện:

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

Lệnh này tạo chứng chỉ mới và import nó vào kho chứng chỉ cá nhân của máy tính. Mở snap-in MMC certlm.msc, đảm bảo chứng chỉ mới xuất hiện trong phần Personal của certificate store.

Mặc định, self-signed certificate được tạo với cài đặt sau:

  • Thuật toán mật mã: RSA;
  • Độ dài khóa: 2048 bit;
  • Key usage chấp nhận được: Client Authentication và Server Authentication;
  • Chứng chỉ có thể dùng cho: Digital Signature, Key Encipherment;
  • Thời hạn hiệu lực chứng chỉ: 1 năm.

Như bạn thấy, thuộc tính chứng chỉ cho thấy chứng chỉ này có thể dùng cho Client Authentication, nhưng cũng hợp lệ cho Server Authentication.

Cách tạo Self-Signed Certificate trong Windows với PowerShell

Sử dụng cmdlet Get-ChildItem, bạn có thể hiển thị tất cả tham số của chứng chỉ đã tạo bằng Thumbprint:

Get-ChildItem -Path "Cert:\LocalMachine\My" | Where-Object Thumbprint -eq 2175A76B10F843676951965F52A718F635FFA043 | Select-Object *

Cách tạo Self-Signed Certificate trong Windows với 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 : 05/11/2021 06:19:42
NotBefore : 05/11/2020 05:59:42
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
Lưu ý. Self-signed certificate như vậy sẽ hết hạn sau 1 năm từ ngày tạo. Bạn có thể đặt thời hạn hiệu lực khác dùng tùy chọn –NotAfter. Ví dụ, bạn có thể cấp chứng chỉ SSL/TLS có thời hạn 3 năm bằng lệnh sau:

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

Bạn có thể tạo chuỗi chứng chỉ. Trước tiên, tạo root certificate (CA), và dựa trên nó, tạo SSL server certificate:

$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

Để export chứng chỉ đã tạo với private key ra file PFX bảo vệ bằng mật khẩu, bạn cần chỉ định Thumbprint. Nó có thể copy từ kết quả lệnh New-SelfSignedCertificate. Bạn cũng cần chỉ định mật khẩu bảo mật chứng chỉ và chuyển đổi sang định dạng SecureString:

$CertPassword = ConvertTo-SecureString -String "YourPassword" -Force –AsPlainText
Export-PfxCertificate -Cert cert:\LocalMachine\My\2779C7928D055B21AAA0Cfe2F6BE1A5C2CA83B30 -FilePath C:\test.pfx -Password $CertPassword

Cách tạo Self-Signed Certificate trong Windows với PowerShell

Public key của chứng chỉ có thể export như sau:

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

Đảm bảo file *.cer (PFX) xuất hiện trong thư mục chỉ định. Nếu bạn chuột phải nó và chọn menu "Install Certificate", bạn có thể dùng Certificate Import Wizard để thêm chứng chỉ vào trusted root certificates trên máy tính.

Cách tạo Self-Signed Certificate trong Windows với PowerShell

Chọn Cert Store location → Local Machine, Place all certificates in the following store → Trusted Root Certification Authorities.

Cách tạo Self-Signed Certificate trong Windows với PowerShell

Bạn có thể tạo chứng chỉ và ngay lập tức import nó vào Trusted Root Certificate store của máy tính dùng lệnh:
$SelfSignCert=New-SelfSignedCertificate …..
$certFile = Export-Certificate -Cert $SelfSignCert -FilePath C:\ps\export-certname.cer
Import-Certificate -CertStoreLocation Cert:\LocalMachine\AuthRoot -FilePath $certFile.FullName

Public key hoặc file chứng chỉ này có thể triển khai đến tất cả máy tính và server trong miền AD bằng GPO (How to deploy certificates on domain computers using GPO?).

Tạo Self-Signed Certificate với Subject Alternative Names

Một trong những tính năng hữu ích của cmdlet New-SelfSignedCertificate là khả năng tạo chứng chỉ với nhiều tên khác nhau, Subject Alternative Names (SAN).

Lưu ý. Công cụ Makecert.exe, khác với cmdlet New-SelfSignedCertificate, không thể tạo chứng chỉ SAN và Wildcard.

Nếu bạn muốn tạo chứng chỉ với nhiều tên, tên đầu tiên của tham số DnsName sẽ được dùng làm CN (Common Name) của chứng chỉ. Ví dụ, hãy tạo self-signed SAN certificate với các tên sau:

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

Lệnh tạo chứng chỉ sẽ trông như sau:

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

Cách tạo Self-Signed Certificate trong Windows với PowerShell

Cũng có thể tạo chứng chỉ wildcard cho toàn bộ namespace domain. Để làm đó, chỉ định *.contoso.com làm tên server.

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

Tạo Self-Signed Certificate cho Code Signing trên Windows

Trong PoweShell 3.0, cmdlet New-SelfSifgnedCertificate chỉ tạo SSL certificate không thể dùng để ký driver, ứng dụng hoặc script code (khác với chứng chỉ tạo bởi tiện ích MakeCert).

Trong PowerShell phiên bản 5.0 và mới hơn, phiên bản mới của cmdlet New-SelfSifgnedCertificate giờ có thể dùng để cấp Code Signing certificate.

Để tạo self-signed application code signing certificate, chạy lệnh:

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

Bây giờ bạn có thể ký PowerShell Script với self-signed certificate:

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

Nếu bạn nhận cảnh báo UnknownError khi thực thi lệnh, nghĩa là chứng chỉ không được tin cậy, vì nó nằm trong kho chứng chỉ cá nhân của người dùng.

Cách tạo Self-Signed Certificate trong Windows với PowerShell

Bạn cần chuyển nó đến Trusted Root Certificate store (đừng quên định kỳ quét Windows certificate root store để tìm chứng chỉ không tin cậy và đáng ngờ và cập nhật danh sách trusted root certificates).

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

Sau đó, bạn có thể ký PowerShell script của mình với self-signed certificate này.

Sử dụng SHA-256 Self-Signed SSL Certificate trong IIS trên Windows Server IIS

Lưu ý rằng khi tạo self-signed certificate cho IIS qua console Internet Information Manager (Create Self-Signed Certificate action menu), chứng chỉ SSL được tạo dùng thuật toán mã hóa SHA-1. Những chứng chỉ này được coi là không tin cậy bởi nhiều trình duyệt và không thể dùng để thiết lập kết nối an toàn (hoặc bạn có thể thấy lỗi SSL khác). Cmdlet New-SelfSignedCertificate cho phép tạo loại chứng chỉ phổ biến hơn dùng thuật toán SHA-256.

Cách tạo Self-Signed Certificate trong Windows với PowerShell

Bạn có thể gắn self-signed SHA-256 certificate tạo bằng PowerShell vào site IIS trên Windows Server. Nếu bạn tạo SSL certificate bằng PowerShell và đặt nó vào certificate store của máy tính, nó sẽ tự động có sẵn cho các site IIS.

Cách tạo Self-Signed Certificate trong Windows với PowerShell

Khởi động IIS Manager console, chọn site của bạn, và trong tùy chọn Site Binding, chọn chứng chỉ bạn tạo và lưu thay đổi.