本文共 1468 字,大约阅读时间需要 4 分钟。
如下的代码段是关于C#对文件进行加密解密的代码,应该是对小伙伴们有些帮助。
using System;
using System.IO;using System.Security.Cryptography;public class Example19_9
{ public static void Main(){FileStream fsOut = File.Create(@"c:tempencrypted.txt"); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); CryptoStream cs = new CryptoStream(fsOut, tdes.CreateEncryptor(), CryptoStreamMode.Write); StreamWriter sw = new StreamWriter(cs); sw.WriteLine("'Twas brillig, and the slithy toves"); sw.WriteLine("Did gyre and gimble in the wabe."); sw.Flush(); sw.Close(); FileStream fsKeyOut = File.Create(@"c:\tempencrypted.key"); BinaryWriter bw = new BinaryWriter(fsKeyOut); bw.Write( tdes.Key ); bw.Write( tdes.IV ); bw.Flush(); bw.Close();}
}
解密代码如下
using System;
using System.IO;using System.Security.Cryptography;public class Example19_10
{ public static void Main(){TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); FileStream fsKeyIn = File.OpenRead(@"c:tempencrypted.key"); BinaryReader br = new BinaryReader(fsKeyIn); tdes.Key = br.ReadBytes(24); tdes.IV = br.ReadBytes(8); FileStream fsIn = File.OpenRead(@"c:\temp\encrypted.txt"); CryptoStream cs = new CryptoStream(fsIn, tdes.CreateDecryptor(), CryptoStreamMode.Read); StreamReader sr = new StreamReader(cs); Console.WriteLine(sr.ReadToEnd()); sr.Close();}
}
转载于:https://blog.51cto.com/14129393/2376628