Code: Select all
static void Main()
{
string subjectName = "selfsigned";
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates.Find(X509FindType.FindBySubjectName,
subjectName,validOnly: false);
if (certs.Count == 0)
{
Console.WriteLine($"Certificate containing subject '{subjectName}' not found.");
return;
}
X509Certificate2 cert = certs[0];
using (RSA rsa = cert.GetRSAPrivateKey()) // fails here
{
if (rsa == null)
{
Console.WriteLine("Certificate does not have an RSA private key.");
return;
}
... do something with the key
}
}
}
< /code>
Der Code funktioniert z. Bei einem Windows 10 -System (22H2, neuesten Updates), wenn Windows das Dialogfeld "Kennworteintrag" angezeigt wird und das Kennwort korrekt eingegeben wurde, kann ich den privaten Schlüssel verwenden, z. Zum Signieren von Daten. Das Dialogfeld "Passworteintrag" wird nie angezeigt.Unhandled exception. System.Security.Cryptography.CryptographicException: Das angegebene Handle ist ungültig.
at System.Security.Cryptography.CngHelpers.GetProperty(SafeNCryptHandle ncryptHandle, String propertyName, CngPropertyOptions options)
at System.Security.Cryptography.CngKey.get_AlgorithmGroup()
at System.Security.Cryptography.RSACng.set_Key(CngKey value)
at System.Security.Cryptography.RSACng..ctor(CngKey key, Boolean transferOwnership)
at System.Security.Cryptography.X509Certificates.CertificatePal.c.b__68_1(CngKey cngKey)
at System.Security.Cryptography.X509Certificates.CertificatePal.GetPrivateKey[T](Func`2 createCsp, Func`2 createCng)
at System.Security.Cryptography.X509Certificates.CertificateExtensionsCommon.GetPrivateKey[T](X509Certificate2 certificate, Predicate`1 matchesConstraints)
at Program.Main()