6

我正在使用类似于此处找到的代码来创建用于 IIS 的自签名证书:http: //blogs.technet.com/b/vishalagarwal/archive/2009/08/22/generating-a-certificate-自签名使用 powershell 和 certenroll-interfaces.aspx

工作正常,除了我想给它一个友好的名称以便在我想将证书分配给动态创建的站点时更容易找到它。

任何人都知道如何更改上述内容以设置友好名称(我已经尝试过似乎明显无济于事的方法)。

是否有更好的方法通过 PowerShell 创建不提示用户输入信息的证书?

跟进我正在使用的脚本 - 基于上面的 url,但变成了一个 cmdlet:

function Add-SelfSignedCertificate
{
    [CmdletBinding()]
    param
    (
            [Parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$True)]
            [Alias('cn')]
            [string]$CommonName
    )

    $name = new-object -com "X509Enrollment.CX500DistinguishedName.1"
    $name.Encode("CN=$CommonName", 0)

    $key = new-object -com "X509Enrollment.CX509PrivateKey.1"
    $key.ProviderName = "Microsoft RSA SChannel Cryptographic Provider"
    $key.KeySpec = 1
    $key.Length = 1024
    $key.SecurityDescriptor = "D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0x80120089;;;NS)"
    $key.MachineContext = 1
    $key.Create()

    $serverauthoid = new-object -com "X509Enrollment.CObjectId.1"
    $serverauthoid.InitializeFromValue("1.3.6.1.5.5.7.3.1")
    $ekuoids = new-object -com "X509Enrollment.CObjectIds.1"
    $ekuoids.add($serverauthoid)
    $ekuext = new-object -com "X509Enrollment.CX509ExtensionEnhancedKeyUsage.1"
    $ekuext.InitializeEncode($ekuoids)

    $cert = new-object -com "X509Enrollment.CX509CertificateRequestCertificate.1"
    $cert.InitializeFromPrivateKey(2, $key, "")
    $cert.Subject = $name
    $cert.Issuer = $cert.Subject
    $cert.NotBefore = get-date
    $cert.NotAfter = $cert.NotBefore.AddDays(90)
    $cert.X509Extensions.Add($ekuext)
    $cert.Encode()

    $enrollment = new-object -com "X509Enrollment.CX509Enrollment.1"
    $enrollment.InitializeFromRequest($cert)
    $certdata = $enrollment.CreateRequest(0)
    $enrollment.InstallResponse(2, $certdata, 0, "")
}
4

3 回答 3

13

它可能对您的特定用途没有帮助,但在 Windows 8.1 和 Server 2012 中安装了一个新的 Powershell CmdLet,它非常快速且易于使用:

New-SelfSignedCertificate [-CertStoreLocation <String> ] [-CloneCert <Certificate> ] [-DnsName <String> ] [-Confirm] [-WhatIf] [ <CommonParameters>]

更多细节可以在这里找到:https ://docs.microsoft.com/en-us/powershell/module/pkiclient/new-selfsignedcertificate?view=win10-ps

在我的使用中,证书的友好名称一直设置为 CmdLet 中指定的第一个 DnsName。

将证书放置在本地计算机的个人存储中的示例:

New-SelfSignedCertificate -CertStoreLocation cert:\LocalMachine\My -DnsName www.example.com

注意:Powershell 必须以管理员权限启动才能正常工作。

于 2014-05-30T21:40:43.480 回答
3

你可以CertificateFriendlyName直接在你的代码中设置,你只需要知道在哪里做:

$enrollment.InitializeFromRequest($cert)
$enrollment.CertificateFriendlyName = 'whatever'
$certdata = $enrollment.CreateRequest(0)

$key有一个 FriendlyName,但我没有看到它出现在任何地方,所以我认为它对你没有帮助。

于 2012-10-22T20:42:52.597 回答
0

Scott Hanselman 写了一篇关于如何使用 SDK 工具 makecert.exe 创建自签名证书的精彩博客文章。该工具看起来比您引用的帖子中的代码更容易使用。使用 makecert.exe,您可以使用 -n 选项指定主题名称。我已使用该主题名称来引用其他工具(如 signtool.exe)中的证书。虽然,我发现主题名称不必是唯一的,所以我倾向于使用看起来是唯一的指纹值。Signtool 还将接受指纹(通过 /sha1 参数)来识别证书。

于 2012-09-17T16:57:40.540 回答