充气城堡智能卡证书

时间:2011-04-20 09:34:06

标签: c# bouncycastle

我在win 7 professional和c#(VS2010)上工作。我需要签名文件并创建一个PKCS信封。
用于签名的证书在USB智能卡上(我安装了随智能卡提供的加密服务提供商CSP)。
这是我用充气城堡写的代码

private byte[] SignData(byte[] DataTosign)
{
    X509Certificate2 card = GetCertificate();
    Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(card);

    Org.BouncyCastle.Crypto.AsymmetricKeyParameter K = DotNetUtilities.GetKeyPair(card.PrivateKey).Private;

    CmsSignedDataGenerator generator = new CmsSignedDataGenerator();
    generator.AddSigner(K, cert, CmsSignedDataGenerator.EncryptionRsa, CmsSignedDataGenerator.DigestSha1);

    ArrayList certList = new ArrayList();
    certList.Add(cert);

    Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList);
    Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);

    generator.AddCertificates(st1);

    CmsSignedData signedData = generator.Generate("1.2.840.113549.1.7.1", new CmsProcessableByteArray(DataTosign), true);  // <- here is the flag

    return signedData.GetEncoded();
}


public static X509Certificate2 GetCertificate()
{
    X509Store st = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    st.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection col = st.Certificates;
    X509Certificate2 card = null;
    X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, "Certificates", "Select one to sign", X509SelectionFlag.SingleSelection);
    if (sel.Count > 0)
    {
        X509Certificate2Enumerator en = sel.GetEnumerator();
        en.MoveNext();
        card = en.Current;
    }
    st.Close();
    return card;
}

问题出在Org.BouncyCastle.Crypto.AsymmetricKeyParameter K = DotNetUtilities.GetKeyPair(card.PrivateKey).Private; 在哪里我得到了

  

System.Security.Cryptography.CryptographicException(消息指定类型无效)

似乎问题是私钥在智能卡上,但要使用generator.AddSigner,我必须传递私钥。有人可以帮助我如何使用智能卡上的证书进行签名吗?

非常感谢!

0 个答案:

没有答案