首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在c#中从SmartCard读取凭据

如何在c#中从SmartCard读取凭据
EN

Stack Overflow用户
提问于 2012-08-03 15:15:41
回答 1查看 14.1K关注 0票数 4

在我的组织中,用户必须使用SmartCard以交互方式登录到Windows工作站(95、Vista和7)。几乎每天,我们都需要读取存储在SmartCard中的凭据,并将它们与ActiveDirectory进行比较,而无需实现自定义凭据管理器。我们比较的字段是: userPrincialName和sAMAccountName。

您能给我看一段代码,演示如何从SmartCard读取凭据,或者引导我访问internet上的文章/代码吗?

在互联网上搜索建议实现凭证管理器或使用其他语言(如C,C++)。此外,我还读到了这篇文章:由orouit编写的http://www.codeproject.com/Articles/17013/Smart-Card-Framework-for-NET,这是一个使用SmartCards的框架-但我认为这对于我的简单任务来说太多了。你认为如何?

EN

回答 1

Stack Overflow用户

发布于 2012-09-07 12:44:42

如果在windows下开发,一旦您插入智能卡,windows将从智能卡获取所有证书,并将它们放到我的证书存储中。

代码语言:javascript
复制
var smartCardCerts = new List<X509Certificate2>();
var myStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
myStore.Open(OpenFlags.ReadOnly);
foreach(X509Certificate2 cert in myStore.Certificates)
{
  if( !cert.HasPrivateKey ) continue; // not smartcard for sure
  var rsa = cert.PrivateKey as RSACryptoServiceProvider;
  if( rsa==null ) continue; // not smart card cert again
  if( rsa.CspKeyContainerInfo.HardwareDevice ) // sure - smartcard
  {
     // inspect rsa.CspKeyContainerInfo.KeyContainerName Property
     // or rsa.CspKeyContainerInfo.ProviderName (your smartcard provider, such as 
     // "Schlumberger Cryptographic Service Provider" for Schlumberger Cryptoflex 4K
     // card, etc
     var name = cert.Name;
     rsa.SignData(); // to confirm presence of private key - to finally authenticate
  }
}

现在基本上有很多加密API都是通过.NET提供的。但是您也可以直接使用API Crypto API

例如,可以通过以下方式直接访问智能卡

代码语言:javascript
复制
CryptAcquireContext(&hProv,"\\.\<Reader Name>\<Container Name>",...)

其中,读卡器名称是读卡器名称,容器名称是上面代码片段中的任何rsa.KeyContainerName。有多种方式可以访问这样的信息,而Crypto API并不是非常一致或直接的。作为提示,CryptAcquireContext的.NET版本是带有CspParameters的RSACryptoServiceProvider,如果需要,您可以在其中指定容器名称。

在ActiveDirectory中很好地找到用户可以通过System.DirectoryServices.DirectoyEntry和System.DirectoryServices.DirectorySearcher来完成,但不要忘记System.DirectoryServices.ActiveDirectory.Forest和相关的API,它们使得一些事情变得更容易弄清楚。

你就能得到

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11791036

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档