简体   繁体   English

如何检查 X509Certificate2 是否可导出

[英]How to check is X509Certificate2 exportable or not

var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);

var certificates = store.Certificates.Find(
    X509FindType.FindByThumbprint, thumbprint, false);

X509Certificate2 cert = certificates[0];

Now we have X509Certificate2 instance.现在我们有 X509Certificate2 实例。 How to check exportable private key or not?如何检查可导出的私钥? (preferably without trying to export explicitly) (最好不要尝试明确导出)

Another approach I found here: How to determine whether an X509Certificate2 is exportable我在这里找到的另一种方法: 如何确定 X509Certificate2 是否可导出

X509Certificate2.PrivateKey Gets the AsymmetricAlgorithm object that represents the private key associated with a certificate. X509Certificate2.PrivateKey 获取表示与证书关联的私钥的 AsymmetricAlgorithm 对象。

The RSACryptoServiceProvider class is a AsymmetricAlgorithm RSACryptoServiceProvider 类是一个非对称算法

Then get the RSACryptoServiceProvider.CspKeyContainerInfo which is a CspKeyContainerInfo object that has a Exportable property that: Gets a value indicating whether a key can be exported from a key container.然后获取 RSACryptoServiceProvider.CspKeyContainerInfo,它是一个 CspKeyContainerInfo 对象,它具有可导出属性: 获取一个值,该值指示是否可以从密钥容器中导出密钥。

Update: works.更新:有效。 So, if you use RSA certificates, it is acceptable approach.因此,如果您使用 RSA 证书,这是可以接受的方法。

Looking at the reference source , the implementation of the Export method makes the following checks:查看参考源Export方法的实现做了以下检查:

  • That the X509ContentType parameter is Cert , SerializedCert or Pfx . X509ContentType参数是CertSerializedCertPfx
  • When the content type is Pfx it makes a key container permission demand for both Export and Open permissions.当内容类型为Pfx它对ExportOpen权限提出关键容器权限要求。

Beyond this, everything else happens via internal calls to the CLR, so it's much harder to say what demands are made of the caller.除此之外,其他一切都通过对 CLR 的内部调用发生,因此很难说对调用者有什么要求。 I can't observe a check in the source which tests for the exportable flag.我无法观察到测试可导出标志的源中的检查。

This is a scenario where I would suggest you attempt to perform the export and handle any exceptions as feedback;在这种情况下,我建议您尝试执行导出并处理任何异常作为反馈; you cannot reasonably predict the outcome of the call with the information exposed by the certificate.您无法使用证书公开的信息合理预测通话结果。

Use this method:使用这个方法:

public static bool CheckCertificateIsExportable(X509Certificate2 certForCheck, X509ContentType certType)
    {
        try
        {
            certForCheck.Export(certType);
            return true;
        }
        catch
        {
            return false;
        }
    }

How to use:如何使用:

if (CheckCertificateIsExportable(certForCheck, X509ContentType.Pkcs12))
        {
            // Do...
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM