1. 程式人生 > >讀取本地xml進行DES加密、解密

讀取本地xml進行DES加密、解密

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace JHEMR.JHOODCommonLib.Utility
{
    /// <summary>
    /// DES加密、解密
    /// </summary>
    public static class SecurityDES
    {
        //預設金鑰向量  
        private
static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; /// <summary> /// DES加密字串 /// </summary> /// <param name="encryptString"> 待加密的字串 </param> /// <param name="encryptKey">加密金鑰,要求為8位 </param> /// <returns>加密成功返回加密後的字串,失敗返回空字元 </returns>
public static string EncryptDES(string encryptString, string encryptKey) { try { byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); byte[] rgbIV = Keys; byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); DESCryptoServiceProvider dCSP = new
DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Convert.ToBase64String(mStream.ToArray()); } catch (Exception ex) { MessageBoxHelper.ShowInfo(ex.Message.ToString()); return string.Empty; } } /// <summary> /// DES解密字串 /// </summary> /// <param name="decryptString">待解密的字串</param> /// <param name="decryptKey"> 解密金鑰,要求為8位,和加密金鑰相同 </param> /// <returns>解密成功返回解密後的字串,失敗返空 </returns> public static string DecryptDES(string decryptString, string decryptKey) { try { byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey); byte[] rgbIV = Keys; byte[] inputByteArray = Convert.FromBase64String(decryptString); DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray()); } catch (Exception ex) { MessageBoxHelper.ShowInfo(ex.Message.ToString()); return string.Empty; } } } }
     private void btn_leadingout_Click(object sender, EventArgs e)
        {
            string localFilePath = "";
            SaveFileDialog sfd = new SaveFileDialog();
            //設定檔案型別 
            sfd.Filter = "XML(*.XML)|*.XML";
            //設定預設檔案型別顯示順序 
            sfd.FilterIndex = 1;
            //儲存對話方塊是否記憶上次開啟的目錄 
            sfd.RestoreDirectory = true;

            //點了儲存按鈕進入 
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                localFilePath = sfd.FileName.ToString(); //獲得檔案路徑 
                //string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1); //獲取檔名,不帶路徑
                try
                {
                    StreamWriter sw = new StreamWriter(localFilePath, false);

                    if (_dtDiagnosis.Rows.Count > 0)
                    {
                           DataRow[] r= _dtDiagnosis.Select("selected");
                           if (r.Count() <= 0)
                           {
                               MessageBox.Show("請在要匯出行的複選框中打鉤。");
                               sw.Close();
                               return;
                           }
                           DataTable dt = r.CopyToDataTable();
                        dt.TableName = "Diagnosis";
                        System.IO.TextWriter tw = new System.IO.StringWriter();
                        dt.WriteXml(tw);
                        string str = SecurityDES.EncryptDES(tw.ToString(), "12345678");
                        if(string.IsNullOrEmpty(str))
                        {
                            MessageBoxHelper.ShowInfo("匯出失敗,請重試。");
                             sw.Close();
                            return;
                        }
                        sw.WriteLine(str);
                    }
                    sw.Close();
                    MessageBoxHelper.ShowInfo("匯出成功");
                }
                catch(Exception f)
                {
                    MessageBoxHelper.ShowInfo("匯出失敗,請重試");

                }
            }
        }

        private void btn_leadingin_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            fileDialog.Title = "XML";
            fileDialog.Filter = "XML(*XML*)|*.XML*"; //設定要選擇的檔案的型別
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                string file = fileDialog.FileName;//返回檔案的完整路徑  
                string strTxtAll = "";   
                FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None);
                StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("UTF-8"));
                string line = sr.ReadLine();
                strTxtAll = line + "\r\n";
                for (int ac = 0; line != null; ac++)
                {
                    line = sr.ReadLine();
                    strTxtAll += line + "\r\n";
                }
                string xml = SecurityDES.DecryptDES(strTxtAll, "12345678");
                if (string.IsNullOrEmpty(xml))
                {
                    MessageBoxHelper.ShowInfo("匯入失敗,請重試。");
                    sr.Close();
                    fs.Close();
                    return;
                }
                StringReader stream = null;
                XmlTextReader reader = null;
                try
                {
                    DataSet xmlDS = new DataSet();
                    stream = new StringReader(xml);
                    reader = new XmlTextReader(stream);
                    xmlDS.ReadXml(reader);
                    reader.Close();
                    _bl.DiagnoisLeadingin(xmlDS.Tables[0]);
                    //todo'''''
                }
                catch (Exception ex)
                {
                    MessageBoxHelper.ShowInfo("匯入失敗,請重試。");
                    reader.Close();
                }
                sr.Close();
                fs.Close();
            }
        }