1. 程式人生 > 其它 >C#建立數字證書並匯出為pfx,並使用pfx進行非對稱加解密

C#建立數字證書並匯出為pfx,並使用pfx進行非對稱加解密

本文源程式下載: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.RSAEncrypt(x509.PublicKey.Key.ToXmlString(false), myname);  
                    MessageBox.Show("密文是:" + enStr);  
                    string deStr = this.RSADecrypt(x509.PrivateKey.ToXmlString(true), enStr);  
                    MessageBox.Show("明文是:" + deStr);  
                }  
            }  
            store.Close();  
            store = null;  
            storecollection = null;  
        }  
        /// <summary>  
        /// 建立還有私鑰的證書  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        private void btn_createPfx_Click(object sender, EventArgs e)  
        {  
            string MakeCert = "C://Program Files//Microsoft Visual Studio 8//SDK//v2.0//Bin//makecert.exe";  
            string x509Name = "CN=luminji";  
            string param = " -pe -ss my -n /"" + x509Name + "/" " ;  
            Process p = Process.Start(MakeCert, param);  
            p.WaitForExit();  
            p.Close();  
            MessageBox.Show("over");  
        }  
        /// <summary>  
        /// 從pfx檔案讀取證書資訊  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        private void btn_readFromPfxFile(object sender, EventArgs e)  
        {  
            X509Certificate2 pc = new X509Certificate2("luminji.pfx", "123");  
            MessageBox.Show("name:" + pc.SubjectName.Name);  
            MessageBox.Show("public:" + pc.PublicKey.ToString());  
            MessageBox.Show("private:" + pc.PrivateKey.ToString());  
            pc = null;  
        }  
        /// <summary>  
        /// RSA解密  
        /// </summary>  
        /// <param name="xmlPrivateKey"></param>  
        /// <param name="m_strDecryptString"></param>  
        /// <returns></returns>  
        public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)  
        {  
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();  
            provider.FromXmlString(xmlPrivateKey);  
            byte[] rgb = Convert.FromBase64String(m_strDecryptString);  
            byte[] bytes = provider.Decrypt(rgb, false);  
            return new UnicodeEncoding().GetString(bytes);  
        }  
        /// <summary>  
        /// RSA加密  
        /// </summary>  
        /// <param name="xmlPublicKey"></param>  
        /// <param name="m_strEncryptString"></param>  
        /// <returns></returns>  
        public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)  
        {  
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();  
            provider.FromXmlString(xmlPublicKey);  
            byte[] bytes = new UnicodeEncoding().GetBytes(m_strEncryptString);  
            return Convert.ToBase64String(provider.Encrypt(bytes, false));  
        }  

  上文是一個示例程式,一個完整的證書工具類如下:

public sealed class DataCertificate  
    {  
        #region 生成證書  
        /// <summary>  
        /// 根據指定的證書名和makecert全路徑生成證書(包含公鑰和私鑰,並儲存在MY儲存區)  
        /// </summary>  
        /// <param name="subjectName"></param>  
        /// <param name="makecertPath"></param>  
        /// <returns></returns>  
        public static bool CreateCertWithPrivateKey(string subjectName, string makecertPath)  
        {  
            subjectName = "CN=" + subjectName;  
            string param = " -pe -ss my -n /"" + subjectName + "/" ";  
            try  
            {  
                Process p = Process.Start(makecertPath, param);  
                p.WaitForExit();  
                p.Close();  
            }  
            catch (Exception e)  
            {  
                LogRecord.putErrorLog(e.ToString(), "DataCerficate.CreateCertWithPrivateKey");  
                return false;  
            }  
            return true;  
        }  
        #endregion  
 
        #region 檔案匯入匯出  
        /// <summary>  
        /// 從WINDOWS證書儲存區的個人MY區找到主題為subjectName的證書,  
        /// 並匯出為pfx檔案,同時為其指定一個密碼  
        /// 並將證書從個人區刪除(如果isDelFromstor為true)  
        /// </summary>  
        /// <param name="subjectName">證書主題,不包含CN=</param>  
        /// <param name="pfxFileName">pfx檔名</param>  
        /// <param name="password">pfx檔案密碼</param>  
        /// <param name="isDelFromStore">是否從儲存區刪除</param>  
        /// <returns></returns>  
        public static bool ExportToPfxFile(string subjectName, string pfxFileName,  
            string password, bool isDelFromStore)  
        {  
            subjectName = "CN=" + subjectName;  
            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 == subjectName)  
                {  
                    Debug.Print(string.Format("certificate name: {0}", x509.Subject));  
  
                    byte[] pfxByte = x509.Export(X509ContentType.Pfx, password);  
                    using (FileStream fileStream = new FileStream(pfxFileName, 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())  
                            {  
                                LogRecord.putErrorLog("Export pfx error while verify the pfx file!", "ExportToPfxFile");  
                                fileStream.Close();  
                                return false;  
                            }  
                        }  
                        fileStream.Close();  
                    }  
                    if( isDelFromStore == true)  
                        store.Remove(x509);  
                }  
            }  
            store.Close();  
            store = null;  
            storecollection = null;  
            return true;  
        }  
        /// <summary>  
        /// 從WINDOWS證書儲存區的個人MY區找到主題為subjectName的證書,  
        /// 並匯出為CER檔案(即,只含公鑰的)  
        /// </summary>  
        /// <param name="subjectName"></param>  
        /// <param name="cerFileName"></param>  
        /// <returns></returns>  
        public static bool ExportToCerFile(string subjectName, string cerFileName)  
        {  
            subjectName = "CN=" + subjectName;  
            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 == subjectName)  
                {  
                    Debug.Print(string.Format("certificate name: {0}", x509.Subject));  
                    //byte[] pfxByte = x509.Export(X509ContentType.Pfx, password);  
                    byte[] cerByte = x509.Export(X509ContentType.Cert);  
                    using (FileStream fileStream = new FileStream(cerFileName, FileMode.Create))  
                    {  
                        // Write the data to the file, byte by byte.  
                        for (int i = 0; i < cerByte.Length; i++)  
                            fileStream.WriteByte(cerByte[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 (cerByte[i] != fileStream.ReadByte())  
                            {  
                                LogRecord.putErrorLog("Export CER error while verify the CERT file!", "ExportToCERFile");  
                                fileStream.Close();  
                                return false;  
                            }  
                        }  
                        fileStream.Close();  
                    }  
                }  
            }  
            store.Close();  
            store = null;  
            storecollection = null;  
            return true;  
        }  
        #endregion  
 
        #region 從證書中獲取資訊  
        /// <summary>  
        /// 根據私鑰證書得到證書實體,得到實體後可以根據其公鑰和私鑰進行加解密  
        /// 加解密函式使用DEncrypt的RSACryption類  
        /// </summary>  
        /// <param name="pfxFileName"></param>  
        /// <param name="password"></param>  
        /// <returns></returns>  
        public static X509Certificate2 GetCertificateFromPfxFile(string pfxFileName,  
            string password)  
        {  
            try  
            {  
                return new X509Certificate2(pfxFileName, password, X509KeyStorageFlags.Exportable);  
            }  
            catch (Exception e)  
            {  
                LogRecord.putErrorLog("get certificate from pfx" + pfxFileName + " error:" + e.ToString(),  
                    "GetCertificateFromPfxFile");  
                return null;  
            }  
        }  
        /// <summary>  
        /// 到儲存區獲取證書  
        /// </summary>  
        /// <param name="subjectName"></param>  
        /// <returns></returns>  
        public static X509Certificate2 GetCertificateFromStore(string subjectName)  
        {  
            subjectName = "CN=" + subjectName;  
            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 == subjectName)  
                {  
                    return x509;  
                }  
            }  
            store.Close();  
            store = null;  
            storecollection = null;  
            return null;  
        }  
        /// <summary>  
        /// 根據公鑰證書,返回證書實體  
        /// </summary>  
        /// <param name="cerPath"></param>  
        public static X509Certificate2 GetCertFromCerFile(string cerPath)  
        {  
            try  
            {  
                return new X509Certificate2(cerPath);  
            }  
            catch (Exception e)  
            {  
                LogRecord.putErrorLog(e.ToString(), "DataCertificate.LoadStudentPublicKey");  
                return null;  
            }              
        }  
        #endregion         
    }