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;namespace DataEncrypt
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }        private void button1_Click(object sender, EventArgs e)
        {
            string str = textBoxInput.Text;
            if (str.Length == 0)
            {
                MessageBox.Show("请输入被加密的字符串");
                return;
            }
            //加密
            try
            {
                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
                //随机生成密钥Key和初始化向量IV
                tdes.GenerateKey();
                tdes.GenerateIV();
                byte[] encryptedBytes = EncryptText(str, tdes.Key, tdes.IV);
                File.AppendAllText("C:\\MyData.txt", Encoding.UTF8.GetString(tdes.Key));
                File.AppendAllText("C:\\MyData.txt", "\r\n");
                File.AppendAllText("C:\\MyData.txt", Encoding.UTF8.GetString(tdes.IV));
                File.AppendAllText("C:\\MyData.txt", "\r\n");
                File.AppendAllText("C:\\MyData.txt", Encoding.UTF8.GetString(encryptedBytes));
                
             //   textBoxKey.Text = Encoding.UTF8.GetString(tdes.Key);
                //得到加密后的字节流
                
                //显示加密后的字符串
             //   textBoxInput.Text = Encoding.UTF8.GetString(encryptedBytes);
                //解密
              //  string decryptString = DecryptText(encryptedBytes, tdes.Key, tdes.IV);
                //显示解密后的字符串
              //  textBoxInput.Text = decryptString;
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "出错");
            }        }
        private byte[] EncryptText(string str, byte[] Key, byte[] IV)
        {
            //创建一个内存流
            MemoryStream memoryStream = new MemoryStream();
            //使用传递的私钥和IV创建加密流
            CryptoStream cryptoStream = new CryptoStream(memoryStream,
                new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV),
                CryptoStreamMode.Write);
            //将传递的字符串转换为字节数组
            byte[] toEncrypt = Encoding.UTF8.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();
            }
        }
        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[] decryptBytes = new byte[dataBytes.Length];
            try
            {
                //从解密流中将解密后的数据读到字节数组中
                cryptoStream.Read(decryptBytes, 0, decryptBytes.Length);
                //得到解密后的字符串
                string decryptedString = Encoding.UTF8.GetString(decryptBytes);
                return decryptedString;
            }
            catch (CryptographicException err)
            {
                throw new Exception("解密出错:" + err.Message);
            }
            finally
            {
                cryptoStream.Close();
                memoryStream.Close();
            }
        }
        private void DecryptFromFile()
        {
            
            if (File.Exists("C:\\MyData.txt"))
            {
              //  TripleDESCryptoServiceProvider tdes2 = new TripleDESCryptoServiceProvider();
                StreamReader sr = new StreamReader("C:\\MyData.txt",Encoding.Default);
                
               byte[] Key = System.Text.Encoding.Default.GetBytes(sr.ReadLine());
               byte[] IV = System.Text.Encoding.Default.GetBytes(sr.ReadLine());
                byte[] encryptedBytes = System.Text.Encoding.Default.GetBytes(sr.ReadLine());
                sr.Close();
               
                string decryptString = DecryptText(encryptedBytes, Key, IV);
                textBoxInput.Text = decryptString;
                
            }
            
            
        }        private void button2_Click(object sender, EventArgs e)
        {
            DecryptFromFile();
        }        private void FormMain_Load(object sender, EventArgs e)
        {
            DecryptFromFile();
        }    
       
    }
}

解决方案 »

  1.   

    实验内容
        设计一个Windows应用程序,实现下列功能:
        1. 使用某种加密算法加密窗体上TextBox控件中显示的文字,然后将其保存到文件MyData.txt中。
        2. 程序开始运行时,自动判断加密后的文件是否存在,如果文件存在,则根据以某种方式保存到加密后的文件中的密钥对加密内容进行解密,并将解密后的结果显示在窗体的TextBox控件中。程序运行效果如图8-6所示。实验步骤
    1. 创建一个名为DataEncrypt的Windows应用程序,修改Form1.cs为FormMain.cs。
    2. 向窗体拖放一个TextBox控件,一个【保存】按钮,一个【打开】按钮。
    3. 在【保存】按钮的Click事件中,创建MyData.txt文件,先将加密密钥写入文件中,然后再写入加密后的文本内容。
    4. 编写一个DecryptFromFile方法,先读出加密密钥,再读出加密后的文本,并根据读出的密钥进行解密,然后将解密结果显示出来。
    5. 在窗体的Load事件和【打开】按钮的Click事件中分别调用DecryptFromFile方法,完成解密的功能。
      

  2.   

    问题出在把key等二进制数据转换为字符串,以及转换字符串为数据的步骤上:
    ..., Encoding.UTF8.GetString(tdes.Key)  //错误
    byte[] Key = System.Text.Encoding.Default.GetBytes(sr.ReadLine()) //错误原因是:
    1、UTF8不能转换所有的二进制数据。
    2、数据中万一有回车(\n),UTF8也会转换出一个回车,你存储的数据可能变成4行以上。解决方法就是用Convert.ToBase64String,以及Convert.FromBase64String进行编码。