.Net,C#访问X509证书加密的Webservice

//使用X509证书加密解密以及生成证书

#region 生成证书 /// <summary> /// 根据指定的证书名和makecert全路径生成证书(包含公钥和私钥,并保存在MY存储区) /// </summary> /// <param name="subjectName"></param> /// <param name="makecertPath"></param> /// <returns></returns> public static bool CreateCertWithPrivateKey(string subjectName, string makecertPath) { //string makecertPath = "E:\\TFS\\Makecert"; subjectName = "CN=" + subjectName; string param = " -pe -ss my -e 12/31/2099 -n \"" + subjectName + "\" "; try { Process p = Process.Start(makecertPath, param); p.WaitForExit(); p.Close(); Console.WriteLine("Create Key Success"); } 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)
        {
            cerFileName = "my";
            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)
                {
                    Console.WriteLine(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.LocalMachine);
            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


        /// <summary>   
        /// RSA Encrypt, input the public key xml and string need to be encrypted 
        /// </summary>   
        /// <param name="xmlPublicKey">xml format of public key</param>   
        /// <param name="strEncryptString">input string</param>   
        /// <returns>RSA Encrypted String</returns>   
        public static string RSAEncrypt(string xmlPublicKey, string strEncryptString)
        {
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
            provider.FromXmlString(xmlPublicKey);
            byte[] bytes = new UnicodeEncoding().GetBytes(strEncryptString);
            return Convert.ToBase64String(provider.Encrypt(bytes, false));
        } 


        /// <summary>   
        /// RSA 解密   
        /// </summary>   
        /// <param name="xmlPrivateKey"></param>   
        /// <param name="m_strDecryptString"></param>   
        /// <returns></returns>   
        public static 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);
        }

上面是一些公共方法,进行加密和解密,获取证书,等等。

下面方法是调用方法生成证书,获取证书的公钥进行加密,使用私钥进行解密。

            X509Certificate2 cer = new X509Certificate2();

            cer = Cert.GetCertificateFromStore("test");
            string publicKey = cer.PublicKey.Key.ToXmlString(false);
            string privateKey = cer.PrivateKey.ToXmlString(true);
            string m = Cert.RSAEncrypt(publicKey, "abc");
            Console.WriteLine(m);
            string source = Cert.RSADecrypt(privateKey, m);
            Console.WriteLine(source);