如何使用ASP.NET从个人存储加载客户端证书?

时间:2011-11-09 09:43:06

标签: c# asp.net cryptography x509certificate rsacryptoserviceprovider

如何使用ASP.NET从个人商店加载客户端证书?

如果有可能,我可以使用它的密码数据吗?

为此我在ASP.NET 2.0中创建了一个应用程序,它检索客户端证书存储(个人)中安装的所有证书,以便用它创建数字签名。

但它不起作用,我不知道是什么问题

// ...
using System.Security.Cryptography.X509Certificates;

namespace WebApplication4
{
    public partial class _Default : System.Web.UI.Page
    {
        public static string ToHexString(byte[] bytes)
        {
           // ...
        }

        protected void btnSignature_Click(object sender, EventArgs e)
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.OpenExistingOnly);
            X509Certificate2Collection certificates = store.Certificates;

            int a = certificates.Count;

            lbCertCount.Text = System.Convert.ToString(a);

            if (a > 0)
            {
                X509Certificate2 certificate = certificates[1];

                string publicKey = certificate.GetPublicKeyString();
                lbMypublicKey.Text = publicKey + "<br/>";

                // AsymmetricAlgorithm privateKey = certificate.PrivateKey;

                RSACryptoServiceProvider privateKey = certificate.PrivateKey as RSACryptoServiceProvider;

                // test message 
                byte[] buffer = Encoding.Default.GetBytes("Welcome");
                byte[] signature = privateKey.SignData(buffer, new SHA1Managed());
                string me = ToHexString(signature);

                lbSignature.Text = me;


                RSACryptoServiceProvider publicKey1 = certificate.PublicKey.Key as RSACryptoServiceProvider;

                bool verify = publicKey1.VerifyData(buffer, new SHA1Managed(), signature);

                if (verify == true)
                {
                    lbControl.Text = "Signature valid";
                }
                else
                {
                    lbControl.Text = "Signature not Valid";
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

对于所有Google员工:

将此添加到您的Web.Config

<identity impersonate="true" /> 

有关详细信息,请参阅msdn on impersonation

答案 1 :(得分:0)

我猜你已经搞砸了这个ASP.NET应用程序。作为测试工具,实际上您并不打算编写访问个人证书的生产应用程序。存储在Web服务器上?我根本没有研究或测试过您的代码,但我会先检查安全权限。我希望运行ASP.Net工作进程的帐户无法访问个人证书。商店。