public X509Certificate2 _GetCertificate()
{
X509Store store = null;
X509Certificate2Collection certs = null;
var sn = this.StoreName.GetValueOrDefault(SysX509.StoreName.My);
var sl = this.StoreLocation.GetValueOrDefault(SysX509.StoreLocation.LocalMachine);
var xft = this.X509FindType.GetValueOrDefault(SysX509.X509FindType.FindByThumbprint);
try
{
if (this.X509FindBy != null)
{
switch (this.X509FindBy.Value)
{
default:
throw new NotImplementedException("Unsupported X509FindBy method.");
}
}
// Try by looking up in store..
store = new X509Store(sn, sl);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
certs = store.Certificates.Find(xft, this.X509FindValue, false);
if (certs == null || certs.Count == 0)
{
var str = string.Format("No valid certificate found for: {0}", _certificateString);
throw new ApplicationException(str);
}
if (certs.Count > 1)
{
var str = string.Format("More than one matching certificate found for: {0}", _certificateString);
throw new ApplicationException(str);
}
#if false // FIXME: Setup certificate validation on mono
if (!certs[0].Verify())
{
var str = string.Format("Certificate verification failed for: {0}", certificateString);
throw new ApplicationException(str);
}
#endif
// Fix to avoid mono's bug #1201
// See: https://github.com/mono/mono/commit/b52404b35394c9941b521622564e3dc061c95118
if (!string.IsNullOrEmpty(this.KeyContainerName))
{
var csp = new CspParameters();
csp.KeyContainerName = this.KeyContainerName;
csp.Flags = CspProviderFlags.UseExistingKey;
csp.Flags = csp.Flags | (sl == SysX509.StoreLocation.LocalMachine ? CspProviderFlags.UseMachineKeyStore : 0);
certs[0].PrivateKey = new RSACryptoServiceProvider(csp);
}
return certs[0];
}
finally
{
if (store != null)
store.Close();
}
}