Can't bind cert using netsh when importing it with X509Store
Asked Answered
O

2

0

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);
}
Oval answered 21/11, 2017 at 15:54 Comment(4)
Have you tried importing a certificate issued by a certificate provider to make sure that there is a problem with the X509StoreLobeline
why would that matter if it works if i export and import the exact same certificate? (in the exact same location????)Oval
Probably there is an exception being thrown when trying to add your generated certificate via the code, its just to rule out different possibilities to narrow down to the actual issueLobeline
@Lobeline no there is no exception! also i can find it in the certificate manager how would i else export it?Oval
F
1

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);
Ferebee answered 22/1, 2021 at 15:41 Comment(1)
Afterh ours of searching, X509KeyStorageFlags.MachineKeySet is what did it for me! Most Bouncy Examples don't include this.Funderburk
M
-2

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

Menispermaceous answered 17/7, 2020 at 16:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.