当前位置: 开源爱好者 » 编程教程 » C#教程 » 正文

C# 对称算法加密解密文件【代码】演示

C#加、解密文件,运用的对称算法,这是从一个C#WinForm程序中摘取出来的代码,实现某一功能的代码被写入到了按钮的事件处理中,你可以变通一下,将代码取出来用在可以用的地方:

private void button9_Click(object sender, EventArgs e)
{//加密账户依赖文件,然后试着在另一个帐户下打开该文件
    var MyFile = "Form1.cs";
    System.IO.File.Encrypt(MyFile);
}
private void button10_Click(object sender, EventArgs e)
{//解密账户依赖文件
    var MyFile = "Form1.cs";
    System.IO.File.Decrypt(MyFile);
}
private void button11_Click(object sender, EventArgs e)
{//使用对称算法加密解密文件
    var MyFile = "Form1.cs";
    var MyPassword = "40405690";
    var MyEnFile = "MyEnFile.cs";
    var MyDeFile = "MyDeFile.cs";
    //使用对称算法加密文件
    byte[] MyIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
    byte[] MyKey = System.Text.Encoding.UTF8.GetBytes(MyPassword);
    var MyInStream = new System.IO.FileStream(MyFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);
    var MyOutStream = new System.IO.FileStream(MyEnFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
    MyOutStream.SetLength(0);
    byte[] MyBytes = new byte[100];
    var MyInLength = 0;
    var MyLength = MyInStream.Length;
    var MyProvider = new System.Security.Cryptography.DESCryptoServiceProvider();
    var MyCryptoStream = new System.Security.Cryptography.CryptoStream(MyOutStream, MyProvider.CreateEncryptor(MyKey, MyIV), System.Security.Cryptography.CryptoStreamMode.Write);
    while (MyInLength < MyLength)
    {
       int Mylen = MyInStream.Read(MyBytes, 0, 100);
       MyCryptoStream.Write(MyBytes, 0, Mylen);
       MyInLength += Mylen;
    }
    MyCryptoStream.Close();
    MyInStream.Close();
    MyOutStream.Close();
    //使用对称算法解密文件
    var MyFileIn = new System.IO.FileStream(MyEnFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);
    var MyFileOut = new System.IO.FileStream(MyDeFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
    MyFileOut.SetLength(0);
    MyLength = MyFileIn.Length;
    MyInLength = 0;
    var MyDeStream = new System.Security.Cryptography.CryptoStream(MyFileOut, MyProvider.CreateDecryptor(MyKey, MyIV), System.Security.Cryptography.CryptoStreamMode.Write);
    while (MyInLength < MyLength)
    {
      int Mylen = MyFileIn.Read(MyBytes, 0, 100);
      MyDeStream.Write(MyBytes, 0, Mylen);
      MyInLength += Mylen;
    }
    MyDeStream.Close();
    MyFileOut.Close();
    MyFileIn.Close();
    MessageBox.Show("加密解密文件操作成功!", "信息提示", MessageBoxButtons.OK);           
}

 

相关内容:

CopyRight 2018© 开源爱好者 All Rights Reserved 豫ICP备16030607号 隐私声明 网站地图