简体   繁体   中英

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:

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}"

And i get the following error:

SSL Certificate add failed, Error: 1312 A specified logon session does not exist. 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.

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 ?

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.

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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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