自己写的文本文件加密器

昨天搞明白了编码的问题后,就开始写这个有些实用价值的东西。
这个软件实现了文本文件的TripeDES的加密(其它的对称加密是类似的)
学习这个的朋友可以参照一下,希望对你们有帮助。
我不是专门写软件的,更不是软件专业。
说它有用也好,没用也罢。只是兴趣,此前不至空虚罢了。
下面是源程序:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Security.Cryptography;
using System.IO;
using System.Diagnostics;


namespace TripleDES
{
    public partial class TdesEncryptExample : Form
    {
        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TdesEncryptExample));
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.txtKey = new System.Windows.Forms.TextBox();
            this.btnFun = new System.Windows.Forms.Button();
            this.linkLabel1 = new System.Windows.Forms.LinkLabel();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.txtFilePath = new System.Windows.Forms.TextBox();
            this.btnScan = new System.Windows.Forms.Button();
            this.btnExit = new System.Windows.Forms.Button();
            this.label3 = new System.Windows.Forms.Label();
            this.cmbPasswordHelp = new System.Windows.Forms.ComboBox();
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.tsslable = new System.Windows.Forms.ToolStripStatusLabel();
            this.statusStrip1.SuspendLayout();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(25, 37);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(47, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "源文件:";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(25, 108);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(35, 12);
            this.label2.TabIndex = 0;
            this.label2.Text = "密码:";
            //
            // txtKey
            //
            this.txtKey.ImeMode = System.Windows.Forms.ImeMode.On;
            this.txtKey.Location = new System.Drawing.Point(89, 105);
            this.txtKey.Name = "txtKey";
            this.txtKey.Size = new System.Drawing.Size(180, 21);
            this.txtKey.TabIndex = 2;
            this.txtKey.UseSystemPasswordChar = true;
            this.txtKey.MouseLeave += new System.EventHandler(this.txtKey_MouseLeave);
            this.txtKey.MouseEnter += new System.EventHandler(this.txtKey_MouseEnter);
            //
            // btnFun
            //
            this.btnFun.Location = new System.Drawing.Point(168, 168);
            this.btnFun.Name = "btnFun";
            this.btnFun.Size = new System.Drawing.Size(72, 23);
            this.btnFun.TabIndex = 4;
            this.btnFun.Text = "操作";
            this.btnFun.UseVisualStyleBackColor = true;
            this.btnFun.Click += new System.EventHandler(this.btnFun_Click);
            //
            // linkLabel1
            //
            this.linkLabel1.AutoSize = true;
            this.linkLabel1.Location = new System.Drawing.Point(306, 217);
            this.linkLabel1.Name = "linkLabel1";
            this.linkLabel1.Size = new System.Drawing.Size(41, 12);
            this.linkLabel1.TabIndex = 6;
            this.linkLabel1.TabStop = true;
            this.linkLabel1.Text = "夏阳港";
            this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(283, 217);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(17, 12);
            this.label4.TabIndex = 6;
            this.label4.Text = "by";
            //
            // label5
            //
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(298, 112);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(125, 12);
            this.label5.TabIndex = 7;
            this.label5.Text = "(密码长度为6到24位)";
            //
            // txtFilePath
            //
            this.txtFilePath.Location = new System.Drawing.Point(89, 34);
            this.txtFilePath.Name = "txtFilePath";
            this.txtFilePath.Size = new System.Drawing.Size(334, 21);
            this.txtFilePath.TabIndex = 0;
            this.txtFilePath.MouseLeave += new System.EventHandler(this.txtFilePath_MouseLeave);
            this.txtFilePath.MouseEnter += new System.EventHandler(this.txtFilePath_MouseEnter);
            this.txtFilePath.TextChanged += new System.EventHandler(this.txtFilePath_TextChanged);
            //
            // btnScan
            //
            this.btnScan.Location = new System.Drawing.Point(368, 66);
            this.btnScan.Name = "btnScan";
            this.btnScan.Size = new System.Drawing.Size(55, 23);
            this.btnScan.TabIndex = 3;
            this.btnScan.Text = "浏览";
            this.btnScan.UseVisualStyleBackColor = true;
            this.btnScan.Click += new System.EventHandler(this.btnScan_Click);
            //
            // btnExit
            //
            this.btnExit.Location = new System.Drawing.Point(262, 168);
            this.btnExit.Name = "btnExit";
            this.btnExit.Size = new System.Drawing.Size(72, 23);
            this.btnExit.TabIndex = 5;
            this.btnExit.Text = "退出";
            this.btnExit.UseVisualStyleBackColor = true;
            this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(25, 72);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(59, 12);
            this.label3.TabIndex = 0;
            this.label3.Text = "密码提示:";
            //
            // cmbPasswordHelp
            //
            this.cmbPasswordHelp.FormattingEnabled = true;
            this.cmbPasswordHelp.Items.AddRange(new object[] {
            "我的爸爸的名字?",
            "我的妈妈的名字?",
            "我最喜欢的小狗叫什么?",
            "我在哪所学校上的高中?"});
            this.cmbPasswordHelp.Location = new System.Drawing.Point(89, 69);
            this.cmbPasswordHelp.Name = "cmbPasswordHelp";
            this.cmbPasswordHelp.Size = new System.Drawing.Size(240, 20);
            this.cmbPasswordHelp.TabIndex = 1;
            this.cmbPasswordHelp.MouseEnter += new System.EventHandler(this.cmbPasswordHelp_MouseEnter);
            this.cmbPasswordHelp.MouseLeave += new System.EventHandler(this.cmbPasswordHelp_MouseLeave);
            //
            // statusStrip1
            //
            this.statusStrip1.AutoSize = false;
            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.tsslable});
            this.statusStrip1.Location = new System.Drawing.Point(0, 242);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.ShowItemToolTips = true;
            this.statusStrip1.Size = new System.Drawing.Size(474, 22);
            this.statusStrip1.TabIndex = 12;
            this.statusStrip1.Text = "哈 哈 ";
            //
            // tsslable
            //
            this.tsslable.AutoSize = false;
            this.tsslable.Name = "tsslable";
            this.tsslable.Size = new System.Drawing.Size(450, 17);
            this.tsslable.Text = "小朋";
            //
            // TdesEncryptExample
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(474, 264);
            this.Controls.Add(this.statusStrip1);
            this.Controls.Add(this.cmbPasswordHelp);
            this.Controls.Add(this.btnExit);
            this.Controls.Add(this.btnScan);
            this.Controls.Add(this.txtFilePath);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.linkLabel1);
            this.Controls.Add(this.btnFun);
            this.Controls.Add(this.txtKey);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.Name = "TdesEncryptExample";
            this.Text = "文本文件加密器";
            this.Load += new System.EventHandler(this.TdesEncryptExample_Load);
            this.statusStrip1.ResumeLayout(false);
            this.statusStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox txtKey;
        private System.Windows.Forms.Button btnFun;
        private System.Windows.Forms.LinkLabel linkLabel1;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label5;

        #endregion


        public TdesEncryptExample()
        {
            InitializeComponent();
        }

        #region 参数声明
        private TripleDESCryptoServiceProvider crypt = null;
        private bool IsToEncrypt = true;    //指示是进行加密还是解密。
        private byte[] key;
        private byte[] IV;
        private string strMain = "本软件用于对文件文件(.txt)的加密解密";

        #endregion

        private void TdesEncryptExample_Load(object sender, EventArgs e)
        {
            crypt = new TripleDESCryptoServiceProvider();
            key = new byte[24];
            IV = new byte[8];
            tsslable.Text = strMain;
        }

        private string EncryptText(string str, byte[] Key, byte[] IV)
        {
            try
            {
                //创建一个内存流。
                MemoryStream memoryStream = new MemoryStream();

                ICryptoTransform transToBase64 = new ToBase64Transform();
                CryptoStream csEncode = new CryptoStream(memoryStream,
                    transToBase64, CryptoStreamMode.Write);

                //使用传递的私钥和IV创建加密流。
                CryptoStream cryptoStream = new CryptoStream(csEncode,
                    crypt.CreateEncryptor(Key, IV),
                    CryptoStreamMode.Write);

                StreamWriter w = new StreamWriter(cryptoStream);

                try
                {
                    //将字节数组写入加密流,并清除缓冲区
                    w.Write(str);
                    w.Flush();
                    cryptoStream.FlushFinalBlock();

                    //得到加密后的字节数组。
                    byte[] encryptedBytes = memoryStream.ToArray();
                    string encryptedString = Encoding.UTF8.GetString(encryptedBytes);
                    return encryptedString;
                }
                catch (CryptographicException err)
                {
                    throw new Exception("加密出错:" + err.Message);
                }
                finally
                {
                    cryptoStream.Close();
                    memoryStream.Close();
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                return null;
            }
        }

        private string DecryptText(string ToDecryptString, byte[] Key, byte[] IV)
        {
            byte[] ToDecryptBytes=Encoding.UTF8.GetBytes(ToDecryptString);

            //根据加密后的字节数组创建一个内存流。
            MemoryStream memoryStream = new MemoryStream(ToDecryptBytes);

            //Transform string from database64;
            ICryptoTransform transformFromBase64 = new FromBase64Transform();
            CryptoStream csDecode = new CryptoStream(memoryStream,
                transformFromBase64, CryptoStreamMode.Read);

            //使用传递的私钥、IV和内存流创建解密流。
            CryptoStream cryptoStream = new CryptoStream(csDecode,
                crypt.CreateDecryptor(Key, IV),CryptoStreamMode.Read);

            StreamReader sr = new StreamReader(cryptoStream);

            try
            {
                //得到解密后的字符串。
                string decryptedString = sr.ReadToEnd();
                return decryptedString;
            }
            catch (CryptographicException err)
            {
                throw new Exception("解密出错:" + err.Message);
            }
            finally
            {
                sr.Close();
                cryptoStream.Close();
                memoryStream.Close();
            }
        }

        private void SetKeyAndIV(string str)
        {
            //验证密码的可用性.
            if (str.Length == 0)
            {
                throw new Exception("密码为空。");
            }
            if (str.Length < 6)
            {
                throw new Exception("密码设置太短。");
            }
            if (str.Length > 24)
            {
                throw new Exception("密码设置太长。");
            }

            byte[] temp = Encoding.UTF8.GetBytes(str);
            int len = temp.Length;
            for (int i = 0; i < len; i++)
            {
                key[23 - i] = temp[i];
            }

            //填满其余值。
            for (int i = len; i < 24; i++)
            {
                key[23 - i] = (byte)i;
            }

            IV = new byte[8];
            for (int i = 0; i < 8; i++)
            {
                IV[i] = key[i * 3];
            }
        }

        private void btnFun_Click(object sender, EventArgs e)
        {
            string strPath = txtFilePath.Text;
            string saveFilePath;
            string FileName;

            if (strPath == "")
            {
                MessageBox.Show("源文件为空!", "提示", MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation);
                return;
            }
            if (File.Exists(strPath) == false)
            {
                MessageBox.Show("源文件不存在!", "提示", MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation);
                return;
            }

            if (IsTxtFile(strPath)==false)
            {
                MessageBox.Show("本程序只能加密解密文本文件!","提示",
                    MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                return;
            }

            int i1 = strPath.LastIndexOf('.');
            int i2 = strPath.LastIndexOf('\\');
            saveFilePath = strPath.Substring(0, i2);
            FileName = strPath.Substring(i2 + 1, i1 - i2 - 1);

            if (IsToEncrypt == true)
            {
                try
                {
                    SetKeyAndIV(txtKey.Text);
                }
                catch (Exception er)
                {
                    MessageBox.Show("对不起,您的" + er.Message, "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                try
                {
                    //读入加密数据
                    FileStream fs = new FileStream(txtFilePath.Text, FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(fs, Encoding.Default);
                    string strToEncrypt = sr.ReadToEnd();
                    sr.Close();
                    fs.Close();

                    string stringEncrypted = EncryptText(strToEncrypt, key, IV);

                    FileName = FunOfFileName(FileName);
                    string strNewFilename = saveFilePath + "\\" + FileName + "-加密文本.txt";
                    if (File.Exists(strNewFilename))
                    {
                        if (MessageBox.Show("文件\"" + FileName + "-加密文本.txt\"在当前目录下己存在,是否替换?",
                            "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                        {
                            return;
                        }
                    }

                    FileStream fs2 = new FileStream(saveFilePath + "\\" + FileName + "-加密文本.txt",
                        FileMode.Create, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs2);
                    sw.WriteLine("密码提示:" + (cmbPasswordHelp.Text == "" ? "无" : cmbPasswordHelp.Text));
                    sw.Write(stringEncrypted);
                    sw.Flush();
                    sw.Close();
                    fs2.Close();

                    MessageBox.Show("恭喜文件加密成功,加密文档己存于加密文件的同一个目录下。",
                        "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                    return;
                }
            }

            else
            {
                //-------------------------------执行解密操作
                string stringDecrypted;
                try
                {
                    SetKeyAndIV(txtKey.Text);

                    //读取加密string.
                    FileStream fs = new FileStream(strPath,
                        FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(fs);
                    sr.ReadLine();
                    string stringToDecrypt = sr.ReadToEnd();
                    sr.Close();
                    fs.Close();
                    stringDecrypted = DecryptText(stringToDecrypt, key, IV);
                }
                catch
                {
                    MessageBox.Show("对不起,您的密码不正确。",
                        "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                try
                {
                    FileName = FunOfFileName(FileName);
                    string strNewFilename = saveFilePath + "\\" + FileName + "-解密文本.txt";
                    if (File.Exists(strNewFilename))
                    {
                        if (MessageBox.Show("文件\"" + FileName + "-解密文本.txt\"在当前目录下己存在,是否替换?",
                            "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                        {
                            return;
                        }
                    }
                    FileStream fs = new FileStream(strNewFilename,
                     FileMode.Create, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Write(stringDecrypted);
                    sw.Flush();
                    sw.Close();
                    fs.Close();
                }

                catch (Exception err)
                {
                    MessageBox.Show(err.Message, "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                MessageBox.Show("恭喜文件解密成功,解密文档己存于加密文件的同一个目录下。",
                    "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("http://shyanye.cnblogs.com/");
        }

        private void btnScan_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "文本文件(.txt)|*.txt";
            DialogResult temp=openFileDialog.ShowDialog();
            if (temp == DialogResult.OK)
            {
                txtFilePath.Text = openFileDialog.FileName;
            }
        }

        private void txtFilePath_TextChanged(object sender, EventArgs e)
        {
            if (File.Exists(txtFilePath.Text) == true)
            {
                //不是文件文件则直接返回
                if (IsTxtFile(txtFilePath.Text) == false)
                {
                    return;
                }

                FileStream fs = new FileStream(txtFilePath.Text,
                    FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                string str = sr.ReadLine();
                sr.Close();
                fs.Close();

                try
                {
                    //只有前五个字条是下列才认为是进行解密操作
                    if (str.Substring(0, 5) == "密码提示:")
                    {
                        //是执行解密算法
                        cmbPasswordHelp.Text = str.Substring(5);
                        cmbPasswordHelp.Enabled = false;
                        IsToEncrypt = false;
                        return;
                    }
                    throw new Exception();
                }
                catch
                {
                    //是执行加密算法
                    cmbPasswordHelp.Text = "";
                    cmbPasswordHelp.Enabled = true;
                    IsToEncrypt = true;
                }
               

            }
        }

        private bool IsTxtFile(string strPath)
        {
            try
            {
                int i = strPath.LastIndexOf('.');
                string fileType = strPath.Substring(i + 1, 3);
                fileType = fileType.ToLowerInvariant();
                if (fileType == "txt")
                {
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }

        private string FunOfFileName(string fileName)
        {
            try
            {
                int i = fileName.LastIndexOf('-');
                string str = fileName.Substring(i + 1);
                string str2 = fileName.Substring(0, i);
                if (str == "加密文本" || str == "解密文本")
                {
                    return str2;
                }
                return fileName;
            }
            catch
            {
                return fileName;
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtFilePath_MouseEnter(object sender, EventArgs e)
        {
            tsslable.Text = "输入要加密或解密文本的位置";
        }

        private void txtFilePath_MouseLeave(object sender, EventArgs e)
        {
            tsslable.Text = strMain;
        }

        private void cmbPasswordHelp_MouseEnter(object sender, EventArgs e)
        {
            tsslable.Text = "可以保留一个密码提示,以防您将来忘记密码";
        }

        private void cmbPasswordHelp_MouseLeave(object sender, EventArgs e)
        {
            tsslable.Text = strMain;
        }

        private void txtKey_MouseEnter(object sender, EventArgs e)
        {
            tsslable.Text = "在此输入您的密码";
        }

        private void txtKey_MouseLeave(object sender, EventArgs e)
        {
            tsslable.Text = strMain;
        }
    }
}


下载
原文地址:https://www.cnblogs.com/shyanye/p/1077969.html