TripleDES对称加密解密小软件

弱弱的我做的一个简单傻瓜的文本加密。
VSC#。NET 2005

这是我对于加密方面的一个练习,之所以把加密后数据存为数字形式,是因为我发现存为Unicode或者其它格式时,从txtbox里再读入时都会使信息发生变化,有人可以告诉我这该怎么处理吗?
谢谢~

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.label3 = new System.Windows.Forms.Label();
            this.txtKey = new System.Windows.Forms.TextBox();
            this.btnEncrypt = new System.Windows.Forms.Button();
            this.btnDecrypt = new System.Windows.Forms.Button();
            this.txtDecrypt = new System.Windows.Forms.RichTextBox();
            this.txtEncrypt = new System.Windows.Forms.RichTextBox();
            this.linkLabel1 = new System.Windows.Forms.LinkLabel();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(22, 15);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(65, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "原始字符串";
            //
            // label2
            //
            this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(22, 331);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(29, 12);
            this.label2.TabIndex = 0;
            this.label2.Text = "密码";
            //
            // label3
            //
            this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(22, 158);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(89, 12);
            this.label3.TabIndex = 0;
            this.label3.Text = "加密后的字符串";
            //
            // txtKey
            //
            this.txtKey.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtKey.ImeMode = System.Windows.Forms.ImeMode.On;
            this.txtKey.Location = new System.Drawing.Point(73, 328);
            this.txtKey.Name = "txtKey";
            this.txtKey.Size = new System.Drawing.Size(285, 21);
            this.txtKey.TabIndex = 2;
            this.txtKey.UseSystemPasswordChar = true;
            //
            // btnEncrypt
            //
            this.btnEncrypt.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnEncrypt.Location = new System.Drawing.Point(199, 368);
            this.btnEncrypt.Name = "btnEncrypt";
            this.btnEncrypt.Size = new System.Drawing.Size(75, 23);
            this.btnEncrypt.TabIndex = 3;
            this.btnEncrypt.Text = "加密";
            this.btnEncrypt.UseVisualStyleBackColor = true;
            this.btnEncrypt.Click += new System.EventHandler(this.btnEncrypt_Click);
            //
            // btnDecrypt
            //
            this.btnDecrypt.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnDecrypt.Location = new System.Drawing.Point(303, 368);
            this.btnDecrypt.Name = "btnDecrypt";
            this.btnDecrypt.Size = new System.Drawing.Size(75, 23);
            this.btnDecrypt.TabIndex = 4;
            this.btnDecrypt.Text = "解密";
            this.btnDecrypt.UseVisualStyleBackColor = true;
            this.btnDecrypt.Click += new System.EventHandler(this.btnDecrypt_Click);
            //
            // txtDecrypt
            //
            this.txtDecrypt.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtDecrypt.Location = new System.Drawing.Point(24, 39);
            this.txtDecrypt.Name = "txtDecrypt";
            this.txtDecrypt.Size = new System.Drawing.Size(476, 106);
            this.txtDecrypt.TabIndex = 0;
            this.txtDecrypt.Text = "";
            //
            // txtEncrypt
            //
            this.txtEncrypt.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtEncrypt.Location = new System.Drawing.Point(24, 185);
            this.txtEncrypt.Name = "txtEncrypt";
            this.txtEncrypt.Size = new System.Drawing.Size(476, 125);
            this.txtEncrypt.TabIndex = 1;
            this.txtEncrypt.Text = "";
            //
            // linkLabel1
            //
            this.linkLabel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.linkLabel1.AutoSize = true;
            this.linkLabel1.Location = new System.Drawing.Point(435, 395);
            this.linkLabel1.Name = "linkLabel1";
            this.linkLabel1.Size = new System.Drawing.Size(41, 12);
            this.linkLabel1.TabIndex = 5;
            this.linkLabel1.TabStop = true;
            this.linkLabel1.Text = "夏阳港";
            this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
            //
            // label4
            //
            this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(412, 395);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(17, 12);
            this.label4.TabIndex = 6;
            this.label4.Text = "by";
            //
            // label5
            //
            this.label5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(367, 335);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(125, 12);
            this.label5.TabIndex = 7;
            this.label5.Text = "(密码长度为6到24位)";
            //
            // TdesEncryptExample
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(524, 421);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.linkLabel1);
            this.Controls.Add(this.txtEncrypt);
            this.Controls.Add(this.txtDecrypt);
            this.Controls.Add(this.btnDecrypt);
            this.Controls.Add(this.btnEncrypt);
            this.Controls.Add(this.txtKey);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "TdesEncryptExample";
            this.Text = "tdes对称加密";
            this.Load += new System.EventHandler(this.TdesEncryptExample_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox txtKey;
        private System.Windows.Forms.Button btnEncrypt;
        private System.Windows.Forms.Button btnDecrypt;
        private System.Windows.Forms.RichTextBox txtDecrypt;
        private System.Windows.Forms.RichTextBox txtEncrypt;
        private System.Windows.Forms.LinkLabel linkLabel1;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label5;


        public TdesEncryptExample()
        {
            InitializeComponent();
            key = new byte[24];
            IV = new byte[8];
        }

        #region 参数声明
        private byte[] key;
        private byte[] IV;

        #endregion

        private void TdesEncryptExample_Load(object sender, EventArgs e)
        {
            key = new byte[24];
            IV = new byte[8];
        }

        private byte[] EncryptText(string str, byte[] Key, byte[] IV)
        {
            try
            {
                //创建一个内存流。
                MemoryStream memoryStream = new MemoryStream();
                //使用传递的私钥和IV创建加密流。
                CryptoStream cryptoStream = new CryptoStream(memoryStream,
                    new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV),
                    CryptoStreamMode.Write);
                //将传递的字符串转换为字节数组。
                byte[] toEncrypt = Encoding.Unicode.GetBytes(str);

                try
                {
                    //将字节数组写入加密流,并清除缓冲区
                    cryptoStream.Write(toEncrypt, 0, toEncrypt.Length);
                    cryptoStream.FlushFinalBlock();
                    //得到加密后的字节数组。
                    byte[] encryptedBytes = memoryStream.ToArray();
                    return encryptedBytes;
                }
                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(byte[] dataBytes, byte[] Key, byte[] IV)
        {
            //根据加密后的字节数组创建一个内存流。
            MemoryStream memoryStream = new MemoryStream(dataBytes);
            //使用传递的私钥、IV和内存流创建解密流。
            CryptoStream cryptoStream = new CryptoStream(memoryStream,
                new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV),
                CryptoStreamMode.Read);
            //创建一个字节数组保存解密后的数据。
            byte[] decryptedBytes = new byte[dataBytes.Length];
            try
            {
                //从解密流中将解密后的数据读到字节数组中。
                cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length);

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

        private void SetKeyAndIV(string str)
        {
            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 btnEncrypt_Click(object sender, EventArgs e)
        {
            if (txtDecrypt.Text == "")
            {
                MessageBox.Show("加密文档为空!", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            int len = txtKey.Text.Length;
            if (len > 24)
            {
                MessageBox.Show("密码长度不能大于24个字符!", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (len < 6)
            {
                MessageBox.Show("密码长度不能小于6个字符!");
                return;
            }

            //初始化key和iv
            SetKeyAndIV(txtKey.Text);
            byte[]encryptedBytes=EncryptText(txtDecrypt.Text, key, IV);

            if (encryptedBytes != null)
            {
                string str = BytesToString(encryptedBytes);
                txtEncrypt.Text=str;
            }
        }

        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            if (txtEncrypt.Text == "")
            {
                MessageBox.Show("解密数据为空!", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            int len = txtKey.Text.Length;
            if (len > 24 || len < 6)
            {
                MessageBox.Show("对不起,您的密码输入错误!","提示",
                    MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                return;
            }

            SetKeyAndIV(txtKey.Text);
            try
            {
                //解密。
                byte[] encryptedBytes = StringToBytes(txtEncrypt.Text);
                string decryptString = DecryptText(encryptedBytes, key, IV);
                txtDecrypt.Text = decryptString;
            }
            catch (Exception err)
            {
                MessageBox.Show("解密出现错误,可能是您的密码或者加密数据有误。", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }


        private string BytesToString(byte[]dataBytes)
        {
            int len = dataBytes.Length;

            string str=len.ToString();
            for (int i = 0; i < len; i++)
            {
                str += "-" + ((int)dataBytes[i]);
            }
            return str;
        }


        private byte[] StringToBytes(string dataString)
        {
            int i,i1, i2;
            i1 = dataString.IndexOf('-');
            int len = int.Parse(dataString.Substring(0,i1));

            byte[] by = new byte[len];
            i2 = i1;

            for(i=0;i<len-1;i++)
            {
                i1 = i2;
                i2 = dataString.IndexOf('-', i1+1);
                by[i]=(byte)(int.Parse(dataString.Substring(i1+1,i2-i1-1)));
            }
            by[i]=(byte)(int.Parse(dataString.Substring(i2+1)));

            return by;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("mailto:hejw06@tsinghua.edu.cn");
        }
    }
}

原文地址:https://www.cnblogs.com/shyanye/p/1049597.html