自签名证书用途很广,测试,开发,本地或者云端网站(比如Microsoft Azure Web Site)都会使用到。本文会介绍一种在Win8.1和Win2012 R2上使用PowerShell快速生成自签名证书,自动导出私钥并在LocalMachine\My和LocalMachine\Root下自动安装的方法。非常易用。[这里是完整的脚本下载链接 CodePlex 或者 GitHub]
目前来说,我们已有的创建Self-Signed证书方法包括用MakeCert和CertMgr的,用SelfSSL或SelfSSL7的,用IIS 7/8自带功能的,或者用比较复杂的PowerShell脚本. 这些方法会要求记住多个命令行复杂的参数,或者手工UI操作,或者对证书生成的细节逻辑有比较深的认识。这里的脚本方法是使用新系统下自带的Powershell PKI Cmdlet, 只需要告诉最基本的证书Subject, 私钥保护密码,和导出私钥的路径即可:
GenerateSelfSignedCert www.mytest.com MyTestPassword c:\temp\mytest.pfx
使用的函数定义如下
<# .DESCRIPTION SelfSignedCertificate AutoScript .NOTES Author: Freist LiLast Updated: 10/30/2014#>#Cert Genearation Related Functions#********************************************************************************************************************#Create Cert, install Cert to My, install Cert to Root, Export Cert as pfxFunction GenerateSelfSignedCert{Param ($certcn,$password,$certfilepath)#Check if the certificate name was used before$thumbprintA=(dir cert:\localmachine\My -recurse | where {$_.Subject -match "CN=" + $certcn} | Select-Object -Last 1).thumbprintif ($thumbprintA.Length -gt 0){Write-Host "Duplicated Cert Name used" -ForegroundColor Cyanreturn}else{$thumbprintA=New-SelfSignedCertificate -DnsName $certcn -CertStoreLocation cert:\LocalMachine\My |ForEach-Object{ $_.Thumbprint}}#If generated successfullyif ($thumbprintA.Length -gt 0) {#query the new installed cerificate again$thumbprintB=(dir cert:\localmachine\My -recurse | where {$_.Subject -match "CN=" + $certcn} | Select-Object -Last 1).thumbprint#If new cert installed sucessfully with the same thumbprintif($thumbprintA -eq $thumbprintB ){$message = $certcn + " installed into LocalMachine\My successfully with thumprint "+$thumbprintAWrite-Host $message -ForegroundColor Cyan$mypwd = ConvertTo-SecureString -String $password -Force –AsPlainTextWrite-Host "Exporting Certificate as .pfx file" -ForegroundColor CyanExport-PfxCertificate -FilePath $certfilepath -Cert cert:\localmachine\My\$thumbprintA -Password $mypwdWrite-Host "Importing Certificate to LocalMachine\Root" -ForegroundColor CyanImport-PfxCertificate -FilePath $certfilepath -Password $mypwd -CertStoreLocation cert:\LocalMachine\Root}else{Write-Host "Thumbprint is not the same between new cert and installed cert." -ForegroundColor Cyan}}else{$message = $certcn + " is not created"Write-Host $message -ForegroundColor Cyan}}
证书产生和安装成功后,PowerShell输出为:
可以在Certificate Manager Console 里面看到:
对于产生的.pfx文件,可以很容易放到Web服务器或者Microsoft AZure云端使用:
更新:
我进一步根据上面的GenerateSelfSignedCert的函数,直接用PowerShell完善了UI部分和自动生成脚本部分。这样使用的时候会弹出友善的Form窗口,生成你想要的Code, 可以立刻运行Code或者Copy Code到别的机器执行 (因为要安装证书,需要PowerShell或者PowerShell ISE以管理员身份权限打开):