C#创建数字证书并导出为pfx,并使用pfx进行非对称加解密

本文提供了一个C#程序DEMO,演示如何使用MAKECERT创建包含私钥的数字证书,存储到个人证书区,然后将其导出为pfx文件,并设置访问密码。此外,还展示了如何读取pfx文件,提取公钥和私钥,以及利用这些密钥进行数据的加解密。该程序适用于需要通过证书确保客户端数据安全的场景。
摘要由CSDN通过智能技术生成

本文源程序下载:http://download.csdn.net/source/2444494

 

我的项目当中,考虑到安全性,需要为每个客户端分发一个数字证书,同时使用数字证书中的公私钥来进行数据的加解密。为了完成这个安全模块,特写了如下一个DEMO程序,该DEMO程序包含的功能有:

1:调用.NET2.0的MAKECERT创建含有私钥的数字证书,并存储到个人证书区;

2:将该证书导出为pfx文件,并为其指定一个用来打开pfx文件的password;

3:读取pfx文件,导出pfx中公钥和私钥;

4:用pfx证书中的公钥进行数据的加密,用私钥进行数据的解密;

系统界面:

 

代码如下:

/// <summary>  
        /// 将证书从证书存储区导出,并存储为pfx文件,同时为pfx文件指定打开的密码  
        /// 本函数同时也演示如何用公钥进行加密,私钥进行解密  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        private void btn_toPfxFile_Click(object sender, EventArgs e)  
        {  
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);  
            store.Open(OpenFlags.ReadWrite);  
            X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates;  
            foreach (X509Certificate2 x509 in storecollection)  
            {  
                if (x509.Subject == "CN=luminji")  
                {  
                    Debug.Print(string.Format("certificate name: {0}", x509.Subject));  
                    byte[] pfxByte = x509.Export(X509ContentType.Pfx, "123");  
                    using (FileStream  fileStream = new FileStream("luminji.pfx", FileMode.Create))  
                    {  
                        // Write the data to the file, byte by byte.  
                        for (int i = 0; i < pfxByte.Length; i++)  
                            fileStream.WriteByte(pfxByte[i]);  
                        // Set the stream position to the beginning of the file.  
                        fileStream.Seek(0, SeekOrigin.Begin);  
                        // Read and verify the data.  
                        for (int i = 0; i < fileStream.Length; i++)  
                        {  
                            if (pfxByte[i] != fileStream.ReadByte())  
                            {  
                                Debug.Print("Error writing data.");  
                                return;  
                            }  
                        }  
                        fileStream.Close();  
                        Debug.Print("The data was written to {0} " +  
                            "and verified.", fileStream.Name);  
                    }  
                    string myname = "my name is luminji! and i love huzhonghua!";  
                    string enStr = this.RSAEncryp
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值