本文实例讲述了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#程序设计有所帮助。
总结以上是内存溢出为你收集整理的C#实现对文件进行加密解密的方法全部内容,希望文章能够帮你解决C#实现对文件进行加密解密的方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)