使用etoken c#中的非可导出私钥来签名xml请求

时间:2017-03-06 11:36:59

标签: c#

我正在使用数字签名。我们必须生成xml请求并使用私钥对请求进行签名。从etoken获取的私钥是不可导出的。我的调查结果表明,当私钥被标记为不可导出时,无法提取私钥。在这种情况下,如何签署xml请求。请帮忙。

1 个答案:

答案 0 :(得分:1)

最后我得到了解决方案。花了一段时间,因为要求有点罕见。这个链接https://www.codeproject.com/Articles/240655/Using-a-Smart-Card-Certificate-with-NET-Security-i帮助我找到了解决方案。请参考以下代码。对于SignXml()方法,请参阅此msdn链接https://msdn.microsoft.com/en-us/library/ms229745(v=vs.110).aspx

    X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        store.Open(OpenFlags.MaxAllowed);

        // find cert by thumbprint
        var foundCerts = store.Certificates.Find(X509FindType.Thumbprint, "12345", true);

        if (foundCerts.Count == 0)
            return;

        var certForSigning = foundCerts[0];
        store.Close();

        // prepare password
        var pass = new SecureString();
        var passwordstring = "password";

        var chararr = passwordstring.ToCharArray();
        foreach (var i in chararr)
            pass.AppendChar(i);
        // take private key
        var privateKey = certForSigning.PrivateKey as RSACryptoServiceProvider;

        // make new CSP parameters based on parameters from current private key but throw in password
        CspParameters cspParameters = new CspParameters(1,
             privateKey.CspKeyContainerInfo.ProviderName,
             privateKey.CspKeyContainerInfo.KeyContainerName,
             new System.Security.AccessControl.CryptoKeySecurity(),
             pass);
        RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider(cspParameters);

        XmlDocument xmlDoc = new XmlDocument();

        // Load an XML file into the XmlDocument object.
        xmlDoc.PreserveWhitespace = true;
        xmlDoc.Load(path);
        // Sign the XML document. 
        SignXml(xmlDoc, rsaCryptoServiceProvider);