手机
当前位置:查字典教程网 >编程开发 >C#教程 >C#实现对文件进行加密解密的方法
C#实现对文件进行加密解密的方法
摘要:本文实例讲述了C#实现对文件进行加密解密的方法。分享给大家供大家参考。具体如下:usingSystem;usingSystem.IO;usi...

本文实例讲述了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:tempencrypted.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:tempencrypted.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:tempencrypted.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:tempencrypted.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#程序设计有所帮助。

【C#实现对文件进行加密解密的方法】相关文章:

C#技巧之快速删除bin和obj文件夹的方法

C# 如何判断两个文件内容是否相同的方法

C# 读取指定路径配置文件的方法

C#中读写INI文件的方法例子

C#中如何执行存储过程方法

解析StreamReader与文件乱码问题的解决方法

C#给picturebox控件加图片选中状态的2个方法

C# SkinEngine控件 给窗体添加皮肤的方法

C#操作config文件的具体方法

C#利用com操作excel释放进程的解决方法

精品推荐
分类导航