简体   繁体   English

使用 X509Store 导入证书时无法使用 netsh 绑定证书

[英]Can't bind cert using netsh when importing it with X509Store

Well i have generated a certificate with the following code:好吧,我用以下代码生成了一个证书:

public X509Certificate2 GenerateSelfSignedCertificate(string friendlyName, string subjectName, int keyStrength = 2048, int validNumberOfMonths = 3)
{
    // Generating Random Numbers
    var randomGenerator = new CryptoApiRandomGenerator();
    var random = new SecureRandom(randomGenerator);

    // The Certificate Generator
    var certificateGenerator = new X509V3CertificateGenerator();

    // Serial Number
    var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
    certificateGenerator.SetSerialNumber(serialNumber);

    // Signature Algorithm
    const string signatureAlgorithm = "SHA256WithRSA";

    // Issuer and Subject Name
    var subjectDN = new X509Name("CN=" + subjectName);
    var issuerDN = subjectDN;
    certificateGenerator.SetIssuerDN(issuerDN);
    certificateGenerator.SetSubjectDN(subjectDN);

    // Valid For
    var notBefore = DateTime.UtcNow.Date;
    var notAfter = notBefore.AddMonths(validNumberOfMonths);

    //Subject name
    var subjectAltName = new GeneralNames(new GeneralName(GeneralName.DnsName, subjectName));
    certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);

    certificateGenerator.SetNotBefore(notBefore);
    certificateGenerator.SetNotAfter(notAfter);

    // Subject Public Key
    AsymmetricCipherKeyPair subjectKeyPair;
    var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
    var keyPairGenerator = new RsaKeyPairGenerator();
    keyPairGenerator.Init(keyGenerationParameters);
    subjectKeyPair = keyPairGenerator.GenerateKeyPair();

    certificateGenerator.SetPublicKey(subjectKeyPair.Public);

    // Generating the Certificate
    var issuerKeyPair = subjectKeyPair;

    // selfsign certificate
    var certificate = certificateGenerator.Generate(new Asn1SignatureFactory(signatureAlgorithm, issuerKeyPair.Private, random));

    // corresponding private key
    PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

    // merge into X509Certificate2
    var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

    var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());
    if (seq.Count != 9)
        throw new PemException("malformed sequence in RSA private key");

    var rsa = RsaPrivateKeyStructure.GetInstance(seq);
    RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
        rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

    x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
    x509.FriendlyName = friendlyName;
    return x509;
}

Then i add the certificate to the windows certificate store with the following code:然后我使用以下代码将证书添加到 Windows 证书存储:

using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
{
    store.Open(OpenFlags.ReadWrite);
    store.Add(certificate);
}

Then i run the following command: netsh http add sslcert ipport="0.0.0.0:8080" certhash="e3336856798d283c3de7b8984734056b488dfd16" appid="{6e10503e-986e-4b6a-8384-743bb330769c}"然后我运行以下命令: netsh http add sslcert ipport="0.0.0.0:8080" certhash="e3336856798d283c3de7b8984734056b488dfd16" appid="{6e10503e-986e-4b6a-8384-743bb330769c}"

And i get the following error:我收到以下错误:

SSL Certificate add failed, Error: 1312 A specified logon session does not exist. SSL 证书添加失败,错误:1312 指定的登录会话不存在。 It may already have been terminated.它可能已经被终止。

Now if i export the certificate as .PFX , delete it and import it again using certificate manager and run the command above again it works.现在,如果我将证书导出为.PFX ,请删除它并使用certificate manager再次导入它并再次运行上面的命令它可以工作。

So what is wrong here?那么这里有什么问题呢?

I even tried to load the cert i exported with the following code but then i get the same error, so my guess is that something is wrong with X509Store ?我什至尝试加载我使用以下代码导出的证书,但随后出现相同的错误,所以我猜测X509Store

var certs = new X509Certificate2Collection();
certs.Import(@"C:\temp\localhost.pfx", "qwerty", X509KeyStorageFlags.Exportable);
var cert = certs[0];

using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
{
    store.Open(OpenFlags.ReadWrite);
    store.Add(cert);
}

The keypoint is when saving certificate in StoreLocation.LocalMachine, you also need to save certificate's key in LocalMachineKeySet.关键是在StoreLocation.LocalMachine中保存证书时,还需要在LocalMachineKeySet中保存证书的key。

so change所以改变

var certificate = new X509Certificate2(content, "pwd");

to

var certificate = new X509Certificate2(content, "pwd", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);

I faced the same issue.我遇到了同样的问题。 Importing the certificates using Import-PfxCertificate commadlet solves the issue.使用 Import-PfxCertificate 指令导入证书可解决此问题。 But Import-PfxCertificate doesnt support importing certificates using alias name (in case multiple certificates are bundled in the same pfx and you want to import one).但是 Import-PfxCertificate 不支持使用别名导入证书(以防多个证书捆绑在同一个 pfx 中并且您想导入一个)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM