[C#] 取得使用者憑證(Certtificate)資訊

之前寫過一個用C++讀憑證,雖然C#也可以直接用API來寫,不過.NET本身其實有內建簡單的憑證類別可以使用(但很多東西還是沒有~),如果想要讀取憑證的簡單資訊倒是可以直接使用。

之前寫過一個用C++讀憑證,雖然C#也可以直接用API來寫,不過.NET本身其實有內建簡單的憑證類別可以使用(但很多東西還是沒有~),如果想要讀取憑證的簡單資訊倒是可以直接使用。Namespace在System.Security.Cryptography.X509Certificates下。

 

X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection storecollection2 = (X509Certificate2Collection)store.Certificates;

TreeNode mybox = new TreeNode(store.Name);
_computer.Nodes.Add(mybox);
_myCertDict.Clear();
foreach (X509Certificate2 x509 in storecollection2)
{
	TreeNode n = new TreeNode(x509.Subject);
	mybox.Nodes.Add(n);

}
store.Close();

 

另外,Windows API其實有一個可以檢視憑證的資訊的Dialog,所以如果想要檢視憑證資訊的話可以拿來用一下,這樣就不用自己寫啦~。

 

[DllImport("CryptUI.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern Boolean CryptUIDlgViewCertificate(
	ref CRYPTUI_VIEWCERTIFICATE_STRUCT pCertViewInfo,
	ref bool pfPropertiesChanged
);


public struct CRYPTUI_VIEWCERTIFICATE_STRUCT
{
	public int dwSize;
	public IntPtr hwndParent;
	public int dwFlags;
	[MarshalAs(UnmanagedType.LPWStr)]
	public String szTitle;
	public IntPtr pCertContext;
	public IntPtr rgszPurposes;
	public int cPurposes;
	public IntPtr pCryptProviderData; // or hWVTStateData
	public Boolean fpCryptProviderDataTrustedUsage;
	public int idxSigner;
	public int idxCert;
	public Boolean fCounterSigner;
	public int idxCounterSigner;
	public int cStores;
	public IntPtr rghStores;
	public int cPropSheetPages;
	public IntPtr rgPropSheetPages;
	public int nStartPage;
}


private void showCert(X509Certificate2 cert)
{
	// Show the cert
	CRYPTUI_VIEWCERTIFICATE_STRUCT certViewInfo = new CRYPTUI_VIEWCERTIFICATE_STRUCT();
	certViewInfo.dwSize = Marshal.SizeOf(certViewInfo);
	certViewInfo.pCertContext = cert.Handle;
	certViewInfo.szTitle = "Certificate Info";
	certViewInfo.dwFlags = CRYPTUI_DISABLE_ADDTOSTORE;
	certViewInfo.nStartPage = 0;
	bool fPropertiesChanged = false;
	if (!CryptUIDlgViewCertificate(ref certViewInfo, ref fPropertiesChanged))
	{
		//int error = Marshal.GetLastWin32Error();
		//MessageBox.Show(error.ToString());
	}
}

 

Dotblogs 的標籤: ,