• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C#对文件进行加密解密代码

OC/C/C++ 水墨上仙 3015次浏览

C#对文件进行加密解密代码

using System;
using System.IO;
using System.Security.Cryptography;
 
public class Example19_9
{
    public static void Main()
    {
 
        // Create a new file to work with
        FileStream fsOut = File.Create(@"c:\temp\encrypted.txt");
 
        // Create a new crypto provider
        TripleDESCryptoServiceProvider tdes =
            new TripleDESCryptoServiceProvider();
 
        // Create a cryptostream to encrypt to the filestream
        CryptoStream cs = new CryptoStream(fsOut, tdes.CreateEncryptor(),
            CryptoStreamMode.Write);
 
        // Create a StreamWriter to format the output
        StreamWriter sw = new StreamWriter(cs);
 
        // And write some data
        sw.WriteLine("'Twas brillig, and the slithy toves");
        sw.WriteLine("Did gyre and gimble in the wabe.");
        sw.Flush();
        sw.Close();
 
        // save the key and IV for future use
        FileStream fsKeyOut = File.Create(@"c:\\temp\encrypted.key");
 
        // use a BinaryWriter to write formatted data to the file
        BinaryWriter bw = new BinaryWriter(fsKeyOut);
 
        // write data to the file
        bw.Write( tdes.Key );
        bw.Write( tdes.IV );
 
        // flush and close
        bw.Flush();
        bw.Close();
 
    }
 
}

解密代码如下


 
using System;
using System.IO;
using System.Security.Cryptography;
 
public class Example19_10
{
    public static void Main()
    {
 
        // Create a new crypto provider
        TripleDESCryptoServiceProvider tdes =
            new TripleDESCryptoServiceProvider();
 
        // open the file containing the key and IV
        FileStream fsKeyIn = File.OpenRead(@"c:\temp\encrypted.key");
 
        // use a BinaryReader to read formatted data from the file
        BinaryReader br = new BinaryReader(fsKeyIn);
 
        // read data from the file and close it
        tdes.Key = br.ReadBytes(24);
        tdes.IV = br.ReadBytes(8);
 
        // Open the encrypted file
        FileStream fsIn = File.OpenRead(@"c:\\temp\\encrypted.txt");
 
        // Create a cryptostream to decrypt from the filestream
        CryptoStream cs = new CryptoStream(fsIn, tdes.CreateDecryptor(),
            CryptoStreamMode.Read);
 
        // Create a StreamReader to format the input
        StreamReader sr = new StreamReader(cs);
 
        // And decrypt the data
        Console.WriteLine(sr.ReadToEnd());
        sr.Close();
 
    }
 
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C#对文件进行加密解密代码
喜欢 (0)
加载中……