小编Ana*_*ina的帖子

PrivateKey 抛出了 System.Security.Cryptography.CryptographicException 类型的异常

我正在尝试使用以下代码使用自签名证书:

X509Certificate2 cert = ToCertificate("CN=localhost");


public static X509Certificate2 ToCertificate(this string subjectName,
                                                StoreName name = StoreName.My,
                                                StoreLocation location = StoreLocation.LocalMachine
                                                )
    {
        X509Store store = new X509Store(name, location);

        store.Open(OpenFlags.ReadOnly);

        try
        {
            var cert = store.Certificates.OfType<X509Certificate2>().FirstOrDefault(c => c.Subject.Equals(subjectName, StringComparison.OrdinalIgnoreCase));

            return cert != null ? new X509Certificate2(cert) : null;
        }
        catch (Exception)
        {

            throw;
        }
        finally
        {
            store.Certificates.OfType<X509Certificate2>().ToList().ForEach(c => c.Reset());
            store.Close();
        }
    }
Run Code Online (Sandbox Code Playgroud)

我收到以下异常:

PrivateKey = 'cert.PrivateKey' threw an exception of type 'System.Security.Cryptography.CryptographicException'
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我试过这个修复这个修复

但是还是有问题!

c# digital-certificate x509certificate2

5
推荐指数
2
解决办法
1万
查看次数

标签 统计

c# ×1

digital-certificate ×1

x509certificate2 ×1