c# - C# 中来自智能卡的证书

标签 c# certificate smartcard

如何确保我从我的智能卡访问证书而不是在 c# 中形成我的个人证书存储? 以及如何让我的 RSACryptoProvider 使用我的智能卡证书私钥?

谢谢

沃利

最佳答案

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

伪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);
}

关于c# - C# 中来自智能卡的证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/566179/

相关文章:

smartcard - 使 JavaCard 小程序可更新的正确方法是什么?

c# - 使用C#动态缺少的编译器的ASP.NET Core 1.1编译所需的成员 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'

java - 将 JRE 设置为使用 Windows 信任库,特别是用户的信任库

ssl - 哪个 CA 颁发时间戳证书

java SunPKCS11 多个 etokens(智能卡)同时,找不到提供者错误

smartcard - 智能卡 : Get certificates content with APDU commands

c# - 重置统一 AR session 以在 iOS 上查找可跟踪的平面

c# - 通过 Google Apps 和 ASP.net 应用程序使用 Google 联合登录

c# - Math.Round 返回奇数向上舍入但偶数向下舍入

ios - 一张证书支持多个应用程序