现在的位置: 首页 > 综合 > 正文

[★] 加密和解密 本地文档

2012年01月19日 ⁄ 综合 ⁄ 共 1948字 ⁄ 字号 评论关闭

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 JiaMi
{
    public partial class Form1 : Form
    {
        //表示所有对称算法的实现都必须从中继承的抽象基类
        public SymmetricAlgorithm symm = null;

        public Form1()
        {
            symm = new RijndaelManaged();
          
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string file = @"F:\3.txt"; //原始文件

                string tempfile = @"F:\4.txt";//加密之后存放文件的路径

                FileStream fsIn = File.Open(file, FileMode.Open, FileAccess.Read);

                FileStream fsOut = File.Open(tempfile, FileMode.Open, FileAccess.Write);
             

                //定义对称算法对象实例和接口
            
                ICryptoTransform transform = symm.CreateEncryptor();
                CryptoStream cstream = new CryptoStream(fsOut, transform, CryptoStreamMode.Write);

                BinaryReader br = new BinaryReader(fsIn);
                // 读取源文件到cryptostream
                cstream.Write(br.ReadBytes((int)fsIn.Length), 0, (int)fsIn.Length);
                cstream.FlushFinalBlock();
                cstream.Close();

                fsOut.Close();
                fsIn.Close();
                this.textBox2.Text = tempfile;

            }
            catch (Exception ex)
            {
                throw ex;
           }
                 
        }
        private void button3_Click(object sender, EventArgs e)
        {
            string tempfile = this.textBox2.Text;

            FileStream fsIn = File.Open(tempfile, FileMode.Open, FileAccess.Read);
            //定义对称算法对象实例和接口
 
            ICryptoTransform transform = symm.CreateDecryptor();

            CryptoStream cstream = new CryptoStream(fsIn, transform, CryptoStreamMode.Read);

            StreamReader sr = new StreamReader(cstream);
            this.textBox3.Text = sr.ReadToEnd();
            fsIn.Close();
        }

              }
}

抱歉!评论已关闭.