.net 查明私钥是否位于硬件设备上,而设备不存在
我想知道证书的私钥是否存储在硬件设备中。.net 查明私钥是否位于硬件设备上,而设备不存在,.net,smartcard,.net,Smartcard,我想知道证书的私钥是否存储在硬件设备中。 让我们假设以下应用程序 class Program { static void Main(string[] args) { try { X509Store store = new X509Store("MY", StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenE
让我们假设以下应用程序
class Program
{
static void Main(string[] args)
{
try
{
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
foreach (X509Certificate2 x509 in store.Certificates)
{
if (x509.HasPrivateKey)
{
AsymmetricAlgorithm a = x509.PrivateKey;
RSACryptoServiceProvider r = a as RSACryptoServiceProvider;
if (null != r)
{
System.Console.WriteLine("hardware: " + r.CspKeyContainerInfo.HardwareDevice);
System.Console.WriteLine("Subject: " + x509.Subject);
System.Console.WriteLine("container: " + r.CspKeyContainerInfo.KeyContainerName);
System.Console.WriteLine("---");
}
}
}
}
catch (CryptographicException ex)
{
Console.WriteLine("Information could not be written out for this certificate.");
}
}
}
我要查找的信息位于r.CspKeyContainerInfo.HardwareDevice
但不幸的是,对于基本智能卡csp提供的商店,我会在执行PrivateKey(如果当时没有smardcard)时收到提示插入设备。
有没有办法在不弹出“请插入智能卡”对话框的情况下获取相同的信息?我注意到,我所有的智能卡证书都有两个属性,而其他证书没有。可以使用
CERT\u SCARD\u PIN\u ID\u PROP\u ID
或CERT\u SCARD\u INFO\u PROP\u ID
进行查询。我不知道这是否是确定的,但它对我有效
此示例应仅列出智能卡证书:
类程序
{
[System.Runtime.InteropServices.DllImport(“crypt32.dll”,SetLastError=true)]
外部公共静态bool CertGetCertificateContextProperty(IntPtr pCertContext、Int32 dwPropId、IntPtr pvData、ref Int32 pcbData);
const int CERT\u SCARD\u PIN\u ID\u PROP\u ID=90;
const int CERT\u SCARD\u INFO\u PROP\u ID=91;
静态布尔证书HASPROPERTY(x509证书x509,int propId)
{
int cbData=0;
//如果属性存在,CertGetCertificateContextProperty返回true
//并将cbData设置为保存数据所需的缓冲区大小。
返回CertGetCertificateContextProperty(x509.Handle,propId,IntPtr.Zero,ref cbData);
}
静态void Main(字符串[]参数)
{
X509Store store=新的X509Store(“我的”,StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
foreach(X509Certificate2 x509店内证书)
{
if(证书财产(x509,证书信息和财产ID))
{
Console.WriteLine(“主题:+x509.Subject”);
}
}
}
}