自签名证书用途很广,测试,开发,本地或者云端网站(比如Microsoft Azure Web Site)都会使用到。本文会介绍一种在Win8.1和Win2012 R2上使用PowerShell快速生成自签名证书,自动导出私钥并在LocalMachineMy和LocalMachineRoot下自动安装的方法。非常易用。[这里是完整的脚本下载链接 CodePlex 或者 GitHub]
目前来说,我们已有的创建Self-Signed证书方法包括用MakeCert和CertMgr的,用SelfSSL或SelfSSL7的,用IIS 7/8自带功能的,或者用比较复杂的PowerShell脚本. 这些方法会要求记住多个命令行复杂的参数,或者手工UI操作,或者对证书生成的细节逻辑有比较深的认识。这里的脚本方法是使用新系统下自带的Powershell PKI Cmdlet, 只需要告诉最基本的证书Subject, 私钥保护密码,和导出私钥的路径即可:
GenerateSelfSignedCert www.mytest.com MyTestPassword c:tempmytest.pfx
使用的函数定义如下
<#
.DESCRIPTION
SelfSignedCertificate AutoScript
.NOTES
Author: Freist Li
Last Updated: 10/30/2014
#>
#Cert Genearation Related Functions
#********************************************************************************************************************
#Create Cert, install Cert to My, install Cert to Root, Export Cert as pfx
Function GenerateSelfSignedCert{
Param (
$certcn,
$password,
$certfilepath
)
#Check if the certificate name was used before
$thumbprintA=(dir cert:localmachineMy -recurse | where {$_.Subject -match "CN=" + $certcn} | Select-Object -Last 1).thumbprint
if ($thumbprintA.Length -gt 0)
{
Write-Host "Duplicated Cert Name used" -ForegroundColor Cyan
return
}
else
{
$thumbprintA=New-SelfSignedCertificate -DnsName $certcn -CertStoreLocation cert:LocalMachineMy |ForEach-Object{ $_.Thumbprint}
}
#If generated successfully
if ($thumbprintA.Length -gt 0)
{
#query the new installed cerificate again
$thumbprintB=(dir cert:localmachineMy -recurse | where {$_.Subject -match "CN=" + $certcn} | Select-Object -Last 1).thumbprint
#If new cert installed sucessfully with the same thumbprint
if($thumbprintA -eq $thumbprintB )
{
$message = $certcn + " installed into LocalMachineMy successfully with thumprint "+$thumbprintA
Write-Host $message -ForegroundColor Cyan
$mypwd = ConvertTo-SecureString -String $password -Force –AsPlainText
Write-Host "Exporting Certificate as .pfx file" -ForegroundColor Cyan
Export-PfxCertificate -FilePath $certfilepath -Cert cert:localmachineMy$thumbprintA -Password $mypwd
Write-Host "Importing Certificate to LocalMachineRoot" -ForegroundColor Cyan
Import-PfxCertificate -FilePath $certfilepath -Password $mypwd -CertStoreLocation cert:LocalMachineRoot
}
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以管理员身份权限打开):
服装店经营模拟游戏 汉化版v0.1
服装店经营模拟游戏是一款玩法简单有趣的3D类型模拟经营游戏,
从细胞到奇点 最新版本v32.42
从细胞到奇点官方正版是一款科学放置游戏,在游戏中玩家需要点击
MY LITTLE PONY魔法公主 安卓版v10.0.0
MY LITTLE PONY魔法公主是一款卡通风格的模拟养成
星露谷物语sve 安卓版v1.5.6.52
星露谷物语sve手机版是游戏的超大拓展Mod内容,全称Sta
动物园大亨 手机版v2.0
动物园大亨是一款模拟动物园经营的休闲放置游戏,采用了卡通画风