欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# txt文件加密与压缩

程序员文章站 2022-06-13 08:02:18
...
  string WinRarDir = GetWinRarDir();
                        WinrarZip(ClearingFileDir, "p_report", dateTime, batchNo.ToString(), Dir, FileName, WinRarDir, "100000000000306");

/// <summary>
        /// 文件打包
        /// </summary>
        /// <param name="OutPutDir">输出路径</param>
        /// <param name="ZipName"></param>
        /// <param name="Date"></param>
        /// <param name="BatchNo"></param>
        /// <param name="FileDir"></param>
        /// <param name="FileName"></param>
        /// <param name="WinRarDir">压缩程序目录</param>
        /// <param name="seatNo">机构代码</param>
        private void WinrarZip(string OutPutDir, string ZipName, string Date, string BatchNo, string FileDir, string FileName, string WinRarDir, string seatNo)
        {
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo(WinRarDir + "\\winrar.exe");
                psi.WindowStyle = ProcessWindowStyle.Hidden;

                //源文件加密
                log.Info("       源文件格式修改为UTF-8");
                SendMsgEdit("       源文件格式修改为UTF-8");
                TransformFile(FileDir + "\\" + FileName, FileDir + "\\" + FileName);
                log.Info("       源文件加密");
                SendMsgEdit("       源文件加密");
                EncryptFile(FileDir + "\\" + FileName, FileDir + "\\" + ZipName + FileName);
                log.Info("       新加密文件添加到TAR包中");
                SendMsgEdit("       新加密文件添加到TAR包中");

                //新加密文件/原文件添加到TAR包中
                //psi.Arguments = string.Format("a -df -av- -ep1 -ibck -afzip {0}{1}_{2}_{3}.tar {4}", OutPutDir, ZipName, Date, BatchNo, FileDir + "\\" + FileName);
                psi.Arguments = string.Format("a -df -av- -ep1 -ibck -afzip {0}{1}_{2}_{3}_{4}.tar {5}", OutPutDir, ZipName, seatNo, Date, BatchNo, FileDir + "\\" + ZipName + FileName);
                Process process = Process.Start(psi);
                process.WaitForExit();


                //TAR包添加到发送包中
                log.Info("       TAR包添加到发送包中");
                SendMsgEdit("       TAR包添加到发送包中");
                psi.Arguments = string.Format("a -av- -ep1 -ibck {0}{1}_{2}_{3}_{4}.tar.gz {5}", OutPutDir, ZipName, seatNo, Date, BatchNo, FileDir + "\\" + ZipName + "_" + seatNo + "_" + Date + "_" + BatchNo + ".tar");
                process = Process.Start(psi);
                process.WaitForExit();
            }
            catch (Exception ex) 
            {
                log.Info(string.Format("快钱正向文件加密发生异常,异常信息:{0}",ex.Message));
                SendMsgEdit(string.Format("快钱正向文件加密发生异常,异常信息:{0}", ex.Message));
            }

        }

        //获取winrar安装路径
        private string GetWinRarDir()
        {
            RegistryKey rkey = Registry.CurrentUser;
            RegistryKey subKey = rkey.OpenSubKey(@"Software\WinRAR SFX", true);
            log.Info("压缩程序安装路径:" + subKey.GetValue(subKey.GetValueNames()[0].ToString()).ToString());
            SendMsgEdit("压缩程序安装路径:" + subKey.GetValue(subKey.GetValueNames()[0].ToString()).ToString());
            return subKey.GetValue(subKey.GetValueNames()[0].ToString()).ToString();
        }

        //txt文件修改为UTF-8
        private void TransformFile(string InputFilename, string OutputFilename)
        {
            FileStream fStream = new FileStream(InputFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            StreamReader sReader = new StreamReader(fStream, Encoding.Default);

            string strRead = sReader.ReadToEnd();
            sReader.Close();
            fStream.Close();

            fStream = new FileStream(OutputFilename, FileMode.Create, FileAccess.Write);
            StreamWriter sWriter = new StreamWriter(fStream, Encoding.UTF8);
            sWriter.Write(strRead);

            sWriter.Close();
            fStream.Close();
        }

        //对文件加密
        private void EncryptFile(string InputFilename, string OutputFilename)
        {
            string strKey = IniFile.GetCfgValue("SubSystem,QP", "DESKey");
            SendMsgEdit("       读取快钱**:" + strKey);
            EncryptDESFile.EncryptFile(InputFilename, OutputFilename, strKey, Encoding.UTF8, FileContentModify);
        }

        /// <summary>
        /// 文件内容前加8个8,文件内容后补空格
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        private string FileContentModify(string strInput)
        {
            string strRead = "88888888" + strInput;
            byte[] byteInput = Encoding.UTF8.GetBytes(strRead);

            return strRead.PadRight(strRead.Length + (8 - byteInput.Length % 8), ' ');
        }



        /// <summary>
        /// 输入内容需要修改与指定输出文件编码的DES文件加密
        /// </summary>
        /// <param name="InputFilename"></param>
        /// <param name="OutputFilename"></param>
        /// <param name="sKey"></param>
        /// <param name="EncryptEncode"></param>
        /// <param name="FileContent"></param>
        public static void EncryptFile(string InputFilename, string OutputFilename, string sKey, Encoding EncryptEncode, FileContentHander FileContent)
        {
            FileStream FileInput = null;
            StreamReader sReader = null;
            FileStream FileOutput = null;
            CryptoStream cryptoStream = null;

            try
            {
                //判断**长度
                sKey = KeyLengthValid(sKey);
                //判断输入文件的编码方式
                Encoding fileEncode = GetType(InputFilename);

                //以文件编码的方式读取
                FileInput = new FileStream(InputFilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                sReader = new StreamReader(FileInput, fileEncode);

                //读入数据
                string strRead = sReader.ReadToEnd();
                if (FileContent != null)
                {
                    strRead = FileContent(strRead);
                }

                //DES加密器
                DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
                DES.Mode = CipherMode.ECB;
                DES.Padding = PaddingMode.None;
                DES.Key = EncryptEncode.GetBytes(sKey);
                DES.IV = EncryptEncode.GetBytes(sKey);

                ICryptoTransform desEncrypt = DES.CreateEncryptor();
                FileOutput = new FileStream(OutputFilename, FileMode.Create, FileAccess.Write);
                cryptoStream = new CryptoStream(FileOutput, desEncrypt, CryptoStreamMode.Write);

                //用加密流写入加密数据
                byte[] byteOutput = EncryptEncode.GetBytes(strRead);
                cryptoStream.Write(byteOutput, 0, byteOutput.Length);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                cryptoStream.Close();
                FileOutput.Close();
                sReader.Close();
                FileInput.Close();
            }
        }