首頁 > 軟體

C#實現對檔案進行加密保護的範例程式碼

2022-12-31 14:01:56

實踐過程

效果

程式碼

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        CheckForIllegalCrossThreadCalls = false;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        FileMenu(Application.ExecutablePath + ",0", Application.ExecutablePath);
        string[] str = Environment.GetCommandLineArgs();
        try
        {
            string strFile = "";
            for (int i = 2; i < str.Length; i++)
                strFile += str[i];
            FileInfo FInfo = new FileInfo(strFile);
            if (FInfo.Extension.ToLower() == ".mr")
            {
                textBox1.Text = strFile;
                button2.Enabled = false;
                button3.Enabled = true;
            }
        }
        catch
        {
        }
    }

    //選擇加密、解密檔案
    private void button1_Click(object sender, EventArgs e)
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            textBox1.Text = openFileDialog1.FileName;
            FileInfo FInfo = new FileInfo(textBox1.Text);
            if (FInfo.Extension.ToLower() == ".mr")
            {
                button2.Enabled = false;
                button3.Enabled = true;
            }
            else
            {
                button2.Enabled = true;
                button3.Enabled = false;
            }
        }
    }

    //加密
    private void button2_Click(object sender, EventArgs e)
    {
        if (textBox1.Text != "")
        {
            if (textBox2.Text.Length < 6)
                MessageBox.Show("密碼不能小於6位!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            else
            {
                EDncrypt myEDncrypt = new EDncrypt(textBox1.Text, textBox2.Text, progressBar1);
                myEDncrypt.StartEncrypt();
                progressBar1.Value = 0;
            }
        }
    }

    //解密
    private void button3_Click(object sender, EventArgs e)
    {
        if (textBox1.Text != "")
        {
            if (textBox2.Text.Length < 6)
                MessageBox.Show("密碼不能小於6位!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            else
            {
                EDncrypt myEDncrypt = new EDncrypt(textBox1.Text, textBox2.Text, progressBar1);
                myEDncrypt.StartDncrypt();
                progressBar1.Value = 0;
            }
        }
    }

    //建立快捷選單
    public static void FileMenu(string strPath, string strName)
    {
        try
        {
            Registry.ClassesRoot.CreateSubKey(".mr");
            RegistryKey RKey1 = Registry.ClassesRoot.OpenSubKey(".mr", true);
            RKey1.SetValue("", "mrfile");
            RKey1.Close();
            Registry.ClassesRoot.CreateSubKey("mrfile");
            RegistryKey RKey2 = Registry.ClassesRoot.OpenSubKey("mrfile", true);
            RKey2.CreateSubKey("DefaultIcon");
            RKey2.CreateSubKey("shell");
            RKey2.Close();
            RegistryKey RKey3 = Registry.ClassesRoot.OpenSubKey("mrfile\DefaultIcon", true);
            RKey3.SetValue("", strPath);
            RKey3.Close();
            RegistryKey RKey4 = Registry.ClassesRoot.OpenSubKey("mrfile\shell", true);
            RKey4.CreateSubKey("解密");
            RKey4.Close();
            RegistryKey RKey5 = Registry.ClassesRoot.OpenSubKey("mrfile\shell\解密", true);
            RKey5.CreateSubKey("command");
            RKey5.Close();
            RegistryKey RKey6 = Registry.ClassesRoot.OpenSubKey("mrfile\shell\解密\command", true);
            RKey6.SetValue("", strName + " \F %1");
            RKey6.Close();
        }
        catch
        {
        }
    }
}

#region 加密、解密類

class EDncrypt
{
    #region 定義全域性變數及類物件

    private string strFile = "";
    private string strNewFile = "";
    private string strPwd = "";
    private ProgressBar PBar = null;
    private Thread EThread = null;
    private Thread DThread = null;

    #endregion

    //含引數的建構函式,用來初始化全域性變數及物件
    public EDncrypt(string name, string pwd, ProgressBar pb)
    {
        strFile = name;
        strPwd = pwd;
        PBar = pb;
        EThread = new Thread(new ThreadStart(this.myEThread));
        DThread = new Thread(new ThreadStart(this.myDThread));
    }

    //檔案加密
    private void myEThread()
    {
        byte[] btRKey = new byte[0];
        if (strPwd.Length == 6)
        {
            btRKey = new byte[]
            {
                (byte) strPwd[0], (byte) strPwd[1], (byte) strPwd[2], (byte) strPwd[3], (byte) strPwd[4],
                (byte) strPwd[5], (byte) strPwd[0], (byte) strPwd[1]
            };
        }

        if (strPwd.Length == 7)
        {
            btRKey = new byte[]
            {
                (byte) strPwd[0], (byte) strPwd[1], (byte) strPwd[2], (byte) strPwd[3], (byte) strPwd[4],
                (byte) strPwd[5], (byte) strPwd[6], (byte) strPwd[0]
            };
        }

        if (strPwd.Length >= 8)
        {
            btRKey = new byte[]
            {
                (byte) strPwd[0], (byte) strPwd[1], (byte) strPwd[2], (byte) strPwd[3], (byte) strPwd[4],
                (byte) strPwd[5], (byte) strPwd[6], (byte) strPwd[7]
            };
        }

        FileStream FStream = new FileStream(strFile, FileMode.Open, FileAccess.Read);
        FileStream NewFStream = new FileStream(strFile + ".mr", FileMode.OpenOrCreate, FileAccess.Write);
        NewFStream.SetLength((long) 0);
        byte[] buffer = new byte[0x400];
        int MinNum = 0;
        long length = FStream.Length;
        int MaxNum = (int) (length / ((long) 0x400));
        PBar.Maximum = MaxNum;
        DES myDES = new DESCryptoServiceProvider();
        CryptoStream CStream =
            new CryptoStream(NewFStream, myDES.CreateEncryptor(btRKey, btRKey), CryptoStreamMode.Write);
        while (MinNum < length)
        {
            int count = FStream.Read(buffer, 0, 0x400);
            CStream.Write(buffer, 0, count);
            MinNum += count;
            try
            {
                if (PBar.Value < PBar.Maximum)
                {
                    PBar.Value++;
                }
            }
            catch
            {
            }
        }

        CStream.Close();
        NewFStream.Close();
        FStream.Close();
        File.Delete(strFile);
        MessageBox.Show("檔案加密成功!", "資訊提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

    //執行加密執行緒
    public void StartEncrypt()
    {
        EThread.Start();
    }

    //檔案解密
    private void myDThread()
    {
        FileStream FStream = null;
        FileStream NewFStream = null;
        CryptoStream CStream = null;
        try
        {
            try
            {
                byte[] btRKey = new byte[0];
                if (strPwd.Length == 6)
                {
                    btRKey = new byte[]
                    {
                        (byte) strPwd[0], (byte) strPwd[1], (byte) strPwd[2], (byte) strPwd[3], (byte) strPwd[4],
                        (byte) strPwd[5], (byte) strPwd[0], (byte) strPwd[1]
                    };
                }

                if (strPwd.Length == 7)
                {
                    btRKey = new byte[]
                    {
                        (byte) strPwd[0], (byte) strPwd[1], (byte) strPwd[2], (byte) strPwd[3], (byte) strPwd[4],
                        (byte) strPwd[5], (byte) strPwd[6], (byte) strPwd[0]
                    };
                }

                if (strPwd.Length >= 8)
                {
                    btRKey = new byte[]
                    {
                        (byte) strPwd[0], (byte) strPwd[1], (byte) strPwd[2], (byte) strPwd[3], (byte) strPwd[4],
                        (byte) strPwd[5], (byte) strPwd[6], (byte) strPwd[7]
                    };
                }

                FStream = new FileStream(strFile, FileMode.Open, FileAccess.Read);
                strNewFile = strFile.Substring(0, strFile.Length - 3);
                NewFStream = new FileStream(strNewFile, FileMode.OpenOrCreate, FileAccess.Write);
                NewFStream.SetLength((long) 0);
                byte[] buffer = new byte[0x400];
                int MinNum = 0;
                long length = FStream.Length;
                int MaxNum = (int) (length / ((long) 0x400));
                PBar.Maximum = MaxNum;
                DES myDES = new DESCryptoServiceProvider();
                CStream = new CryptoStream(NewFStream, myDES.CreateDecryptor(btRKey, btRKey),
                    CryptoStreamMode.Write);
                while (MinNum < length)
                {
                    int count = FStream.Read(buffer, 0, 0x400);
                    CStream.Write(buffer, 0, count);
                    MinNum += count;
                    try
                    {
                        if (PBar.Value < PBar.Maximum)
                        {
                            PBar.Value++;
                        }
                    }
                    catch
                    {
                    }
                }

                MessageBox.Show("檔案解密成功!", "資訊提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                MessageBox.Show("檔案解密失敗!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        finally
        {
            CStream.Close();
            FStream.Close();
            NewFStream.Close();
        }
    }

    //執行解密執行緒
    public void StartDncrypt()
    {
        DThread.Start();
    }
}

#endregion
partial class Form1
{
    /// <summary>
    /// 必需的設計器變數。
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// 清理所有正在使用的資源。
    /// </summary>
    /// <param name="disposing">如果應釋放託管資源,為 true;否則為 false。</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows 表單設計器生成的程式碼

    /// <summary>
    /// 設計器支援所需的方法 - 不要
    /// 使用程式碼編輯器修改此方法的內容。
    /// </summary>
    private void InitializeComponent()
    {
        this.label1 = new System.Windows.Forms.Label();
        this.textBox1 = new System.Windows.Forms.TextBox();
        this.button1 = new System.Windows.Forms.Button();
        this.label2 = new System.Windows.Forms.Label();
        this.textBox2 = new System.Windows.Forms.TextBox();
        this.label3 = new System.Windows.Forms.Label();
        this.label4 = new System.Windows.Forms.Label();
        this.progressBar1 = new System.Windows.Forms.ProgressBar();
        this.groupBox1 = new System.Windows.Forms.GroupBox();
        this.button2 = new System.Windows.Forms.Button();
        this.button3 = new System.Windows.Forms.Button();
        this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
        this.groupBox1.SuspendLayout();
        this.SuspendLayout();
        // 
        // label1
        // 
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(6, 17);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(161, 12);
        this.label1.TabIndex = 0;
        this.label1.Text = "請選擇要加密或解密的檔案:";
        // 
        // textBox1
        // 
        this.textBox1.Location = new System.Drawing.Point(32, 35);
        this.textBox1.Name = "textBox1";
        this.textBox1.Size = new System.Drawing.Size(263, 21);
        this.textBox1.TabIndex = 1;
        // 
        // button1
        // 
        this.button1.Location = new System.Drawing.Point(301, 33);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(33, 23);
        this.button1.TabIndex = 2;
        this.button1.Text = "…";
        this.button1.UseVisualStyleBackColor = true;
        this.button1.Click += new System.EventHandler(this.button1_Click);
        // 
        // label2
        // 
        this.label2.AutoSize = true;
        this.label2.Location = new System.Drawing.Point(7, 71);
        this.label2.Name = "label2";
        this.label2.Size = new System.Drawing.Size(83, 12);
        this.label2.TabIndex = 3;
        this.label2.Text = "加/解密密碼:";
        // 
        // textBox2
        // 
        this.textBox2.Location = new System.Drawing.Point(92, 68);
        this.textBox2.Name = "textBox2";
        this.textBox2.PasswordChar = '*';
        this.textBox2.Size = new System.Drawing.Size(151, 21);
        this.textBox2.TabIndex = 4;
        // 
        // label3
        // 
        this.label3.AutoSize = true;
        this.label3.ForeColor = System.Drawing.Color.Red;
        this.label3.Location = new System.Drawing.Point(243, 71);
        this.label3.Name = "label3";
        this.label3.Size = new System.Drawing.Size(95, 12);
        this.label3.TabIndex = 5;
        this.label3.Text = "(密碼應大於6位)";
        // 
        // label4
        // 
        this.label4.AutoSize = true;
        this.label4.Location = new System.Drawing.Point(7, 101);
        this.label4.Name = "label4";
        this.label4.Size = new System.Drawing.Size(83, 12);
        this.label4.TabIndex = 6;
        this.label4.Text = "加/解密進度:";
        // 
        // progressBar1
        // 
        this.progressBar1.Location = new System.Drawing.Point(92, 99);
        this.progressBar1.Name = "progressBar1";
        this.progressBar1.Size = new System.Drawing.Size(242, 18);
        this.progressBar1.TabIndex = 7;
        // 
        // groupBox1
        // 
        this.groupBox1.Controls.Add(this.label1);
        this.groupBox1.Controls.Add(this.progressBar1);
        this.groupBox1.Controls.Add(this.textBox1);
        this.groupBox1.Controls.Add(this.label4);
        this.groupBox1.Controls.Add(this.button1);
        this.groupBox1.Controls.Add(this.label3);
        this.groupBox1.Controls.Add(this.label2);
        this.groupBox1.Controls.Add(this.textBox2);
        this.groupBox1.Location = new System.Drawing.Point(5, 5);
        this.groupBox1.Name = "groupBox1";
        this.groupBox1.Size = new System.Drawing.Size(342, 123);
        this.groupBox1.TabIndex = 8;
        this.groupBox1.TabStop = false;
        this.groupBox1.Text = "檔案加/解密設定";
        // 
        // button2
        // 
        this.button2.Enabled = false;
        this.button2.Location = new System.Drawing.Point(223, 134);
        this.button2.Name = "button2";
        this.button2.Size = new System.Drawing.Size(59, 27);
        this.button2.TabIndex = 9;
        this.button2.Text = "加密";
        this.button2.UseVisualStyleBackColor = true;
        this.button2.Click += new System.EventHandler(this.button2_Click);
        // 
        // button3
        // 
        this.button3.Enabled = false;
        this.button3.Location = new System.Drawing.Point(288, 134);
        this.button3.Name = "button3";
        this.button3.Size = new System.Drawing.Size(59, 27);
        this.button3.TabIndex = 9;
        this.button3.Text = "解密";
        this.button3.UseVisualStyleBackColor = true;
        this.button3.Click += new System.EventHandler(this.button3_Click);
        // 
        // openFileDialog1
        // 
        this.openFileDialog1.FileName = "openFileDialog1";
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(353, 167);
        this.Controls.Add(this.button3);
        this.Controls.Add(this.button2);
        this.Controls.Add(this.groupBox1);
        this.MaximizeBox = false;
        this.Name = "Form1";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "對檔案進行加密保護";
        this.Load += new System.EventHandler(this.Form1_Load);
        this.groupBox1.ResumeLayout(false);
        this.groupBox1.PerformLayout();
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.TextBox textBox1;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.TextBox textBox2;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.Label label4;
    private System.Windows.Forms.ProgressBar progressBar1;
    private System.Windows.Forms.GroupBox groupBox1;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.Button button3;
    private System.Windows.Forms.OpenFileDialog openFileDialog1;
}

到此這篇關於C#實現對檔案進行加密保護的範例程式碼的文章就介紹到這了,更多相關C#檔案加密內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com