I want to create a site with a certificate I use this to generate a certificate:
static byte[] MakeCert()
{
var ecdsa = ECDsa.Create(); // generate asymmetric key pair
var req = new CertificateRequest("cn=foobar", ecdsa, HashAlgorithmName.SHA256);
var cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(20));
//// Create PFX (PKCS #12) with private key
File.WriteAllBytes($"{path}\mycert.pfx", cert.Export(X509ContentType.Pfx, "123456"));
return cert.Export(X509ContentType.Cert);
}
Then I call here:
..
var certBytes = MakeCert();
store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
X509Certificate2 certificate = new X509Certificate2(certBytes, (string)null,
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
store.Add(certificate);
web.CommitChanges();
var site = web.Sites.Add(appName, "http", $"*:{webPort}:{appName}", appDir);
site.ServerAutoStart = true;
var binding = site.Bindings.Add($"*:{sslPort}:{appName}", certificate.GetCertHash(), store.Name);
binding.Protocol = "https";
site.ApplicationDefaults.ApplicationPoolName = appPoolName;
web.CommitChanges();
store.Close();
store.Dispose();
return true;
}
catch (Exception ex)
{
MessageBox.Show($"An error occurred when creating IIS App: {ex.Message}", "Error");
return false;
}
But I get the error:
value does not fall within the expected range.
How to correct this?