在数字安全领域,证书是验证身份和加密数据的关键工具。本文将介绍如何在.NET环境中获取存储在本地计算机上的数字证书信息,特别是如何从“CurrentUser”和“LocalMachine”存储位置检索证书信息。如果需要根据证书名称搜索证书或获取证书哈希,本文将为提供帮助。
尽管已经有许多关于.NET加密类的文章,本文不会深入讨论这些细节,而是推荐阅读之前提到的文章。本文将展示如何访问数字证书信息并使用它,特别是如何从“CurrentUser”和“LocalMachine”存储位置检索信息。最近,需要编写一些代码来根据证书名称或证书密钥找到证书。之后,需要使用该证书的私钥加密一些数据。虽然听起来简单,但在编码时会发现,由于哈希值是编码的,实际上看不到它。因此,必须先获取证书,然后将其转换为字符串。
在项目的核心,有一个名为getCertFromStore
的函数,它将根据请求的证书信息从存储中检索所有证书。它有一个可选参数Name
,用于搜索具有该名称的证书。
以下是VB.NET代码示例:
Public Function getCertFromStore(ByVal pCert_info As X509_Certificate_info, ByRef psError_Msg As String, Optional ByVal Name As String = "") As X509CertificateCollection
Dim certLocation As X509CertificateStore.StoreLocation
If pCert_info.Certficate_Location = "LocalMachine" Then
certLocation = X509CertificateStore.StoreLocation.LocalMachine
ElseIf pCert_info.Certficate_Location = "CurrentUser" Then
certLocation = X509CertificateStore.StoreLocation.CurrentUser
Else
psError_Msg = "Error Setting Location"
Return Nothing
End If
Dim certProvider As X509CertificateStore.StoreProvider
' for this test use system provider
If pCert_info.Provider = "System" Then
' Opening the System Store
certProvider = X509CertificateStore.StoreProvider.System
Else
psError_Msg = "Retrieving certificate data: " & _
"StoreProvider is not SYSTEM Store "
Return Nothing
End If
Dim certStore As X509CertificateStore
' Specify store there certificates reside
If pCert_info.Store_Name.ToUpper = "MY" Then
certStore = New X509CertificateStore(certProvider, _
certLocation, pCert_info.Store_Name)
ElseIf pCert_info.Store_Name.ToUpper = "ROOT" Then
certStore = X509CertificateStore.LocalMachineStore(X509CertificateStore.RootStore.ToString())
Else
psError_Msg = "Unknown Store"
Return Nothing
End If
Try
' Try opening certificate store store
Dim boolOpen As Boolean = certStore.OpenRead()
Catch ex As Exception
psError_Msg = "Can not open certificate store for Provider:" & _
certProvider & _
"Location:" & _
certLocation & _
"Store Name:" & _
pCert_info.Store_Name
Return Nothing
End Try
Dim cersCollection As X509CertificateCollection
If Name <> "" Then
' Search for the certificate in the store based
' on the subject name (exact match)
cersCollection = certStore.FindCertificateBySubjectString(Name)
Else
cersCollection = certStore.Certificates
End If
Return cersCollection
End Function
获取存储中的所有证书后,可以根据需要获取有关各个证书的所有信息。
txtName.Text = certMy.GetName
txtHash.Text = System.Convert.ToBase64String(certMy.GetKeyIdentifier)
还进行了检查,以确保需要使用RSACryptoServiceProvider
时具有私钥。
Try
rsaCSP = CType(certMy.Key, RSACryptoServiceProvider)
MsgBox("You have access to private keys on this certificate", MsgBoxStyle.Information)
' Here you can start encrypting stuff
Catch ex As Exception
MsgBox("Error Getting RSACryptoServiceProvider" & ex.Message, MsgBoxStyle.Critical)
End Try