public X509Certificate2 LoadPrivateKey(string thumbprint, string subjectName, string password)
{
if (m_certificateSubdir == null || !m_certificateSubdir.Exists)
{
return null;
}
if (string.IsNullOrEmpty(thumbprint) && string.IsNullOrEmpty(subjectName))
{
return null;
}
foreach (FileInfo file in m_certificateSubdir.GetFiles("*.der"))
{
try
{
X509Certificate2 certificate = new X509Certificate2(file.FullName);
if (!String.IsNullOrEmpty(thumbprint))
{
if (!string.Equals(certificate.Thumbprint, thumbprint, StringComparison.CurrentCultureIgnoreCase))
{
continue;
}
}
if (!String.IsNullOrEmpty(subjectName))
{
if (!Utils.CompareDistinguishedName(subjectName, certificate.Subject))
{
if (subjectName.Contains("=") || !certificate.Subject.Contains("CN=" + subjectName))
{
continue;
}
}
}
string fileRoot = file.Name.Substring(0, file.Name.Length - file.Extension.Length);
StringBuilder filePath = new StringBuilder();
filePath.Append(m_privateKeySubdir.FullName);
filePath.Append(Path.DirectorySeparatorChar);
filePath.Append(fileRoot);
FileInfo privateKeyFile = new FileInfo(filePath.ToString() + ".pfx");
RSA rsa = null;
try
{
certificate = new X509Certificate2(
privateKeyFile.FullName,
(password == null) ? String.Empty : password,
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
rsa = certificate.GetRSAPrivateKey();
}
catch (Exception)
{
certificate = new X509Certificate2(
privateKeyFile.FullName,
(password == null) ? String.Empty : password,
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.DefaultKeySet);
rsa = certificate.GetRSAPrivateKey();
}
if (rsa != null)
{
int inputBlockSize = rsa.KeySize / 8 - 42;
byte[] bytes1 = rsa.Encrypt(new byte[inputBlockSize], RSAEncryptionPadding.OaepSHA1);
byte[] bytes2 = rsa.Decrypt(bytes1, RSAEncryptionPadding.OaepSHA1);
if (bytes2 != null)
{
// Utils.Trace(1, "RSA: {0}", certificate.Thumbprint);
return certificate;
}
}
}
catch (Exception e)
{
Utils.Trace(e, "Could not load private key for certificate " + subjectName);
}
}
return null;
}