来自SmartCard的证书在C#

编程入门 行业动态 更新时间:2024-10-14 14:18:42
本文介绍了来自SmartCard的证书在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何确保我从我的SmartCard存取凭证,而不是在c#中建立我的个人凭证存放区? 和如何让我的RSACryptoProvider利用我的智能卡证书私钥?

How can I ensure to I am accesing the Certificates from my SmartCard and not form my personal certificate store in c#? and How can I make my RSACryptoProvider to utilize my smart card certificate private key?

感谢

Wally

推荐答案

有时候,特别是如果你没有在智能卡上使用默认密钥容器名不会复制到本地证书存储。解决方案是使用crypto api通过KP_CERTIFICATE访问密钥,从检索的数据构造证书,并为其分配一个使用您自己的密钥容器名称构造的新RSACryptoServiceProvider。

Sometimes, especially if you are not using default key container name on the smart card (recommended by Microsoft), certificates are not copied to local certificate store. The solution is to use crypto api to access the key with KP_CERTIFICATE, construct certificate from the retrieved data, and assign it a new RSACryptoServiceProvider constructed using your own key container name.

伪C#代码如下:

int reti = CryptoApi.CryptGetUserKey(_hprovider, keytype, ref userKey); if (reti) { reti =CryptoApi.CryptGetKeyParam(_userKey, KP_CERTIFICATE, ref pbdata, ref pwddatalen, 0); } if (reti || pwddatalen>0) { byte[] data = new byte[pwddatalen]; ret = CryptoApi.CryptGetKeyParam(_userKey, KP_CERTIFICATE, data, ref pwddatalen, 0); if (ret) { X509Certificate2 c = new X509Certificate2(data); X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, c.Thumbprint, validonly); store.Close(); if (col.Count != 1) { //not found in store - CSP didn't copy it c.PrivateKey = PrivateKey(keytype); return c; } else { return col[0]; } } } private RSACryptoServiceProvider PrivateKey (KeyType keytype) { CspParameters csparms = new CspParameters(); csparms.KeyContainerName = _containerName; csparms.ProviderName = _provider; csparms.ProviderType = 1; csparms.Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseExistingKey; csparms.KeyNumber = (int)keytype; return new RSACryptoServiceProvider(csparms); }

更多推荐

来自SmartCard的证书在C#

本文发布于:2023-11-07 23:39:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567748.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:证书   SmartCard

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!