2012-02-10 197 views
2

我有一个充满证书的密钥库。另一个人告诉我证书有一个私钥,但当我检查我的代码时,我从来没有看到任何。所有这些键都用在vs6和cryptapi中,我使用的是c#。如何判断证书是否有私钥

我创建了自己的证书,并确保它有一个私钥使用方法这里 http://www.source-code.biz/snippets/vbasic/3.htm

当我进口的到相同的密钥库,然后跑到我的代码证书表明,它确实有一个私人密钥,密钥存储区中的所有其他证书都不会(根据我的代码)。

有一些标志或我需要设置的东西,以便能够使用此密钥库中的证书内的私钥?

public void testForPrivateKey(string keystorename) 
{ 
    X509Store teststore = new X509Store(keystorename); 

    teststore.Open(OpenFlags.ReadOnly); 
    foreach (X509Certificate2 cert in teststore.Certificates) 
    { 
     if(cert.HasPrivateKey) 
     { 
      System.Diagnostics.Debug.WriteLine("Private key found certificate name: {0}", cert.Subject); 
     } 

    } 
    store.Close(); 

} 
+0

发现该键是在“密钥容器”,而不是“证书存储”有谁知道我可以指定我会用做加密密钥/解密因为有交换/签名密钥和密钥容器中的其他人。 – user1202605 2012-02-10 22:36:55

回答

1

我得到了同样的问题,但调查后解决: 如果一个证书有私钥,它也具有属性CERT_KEY_SPEC_PROP_ID。

DWORD keySpec; 
DWORD len = 4; 
BOOL ret = CertGetCertificateContextProperty(pCertContext, CERT_KEY_SPEC_PROP_ID, &keySpec, &len); 
if (!ret){ 
    //has no private key 
} 
+0

我没有看到我的证书。你能否详细说明一下? – user3613932 2017-02-23 02:50:17