C#对文件进行加密解密代码
加密代码
usingSystem;
usingSystem.IO;
usingSystem.Security.Cryptography;
publicclassExample19_9
{
publicstaticvoidMain()
{
//Createanewfiletoworkwith
FileStreamfsOut=File.Create(@"c:\temp\encrypted.txt");
//Createanewcryptoprovider
TripleDESCryptoServiceProvidertdes=
newTripleDESCryptoServiceProvider();
//Createacryptostreamtoencrypttothefilestream
CryptoStreamcs=newCryptoStream(fsOut,tdes.CreateEncryptor(),
CryptoStreamMode.Write);
//CreateaStreamWritertoformattheoutput
StreamWritersw=newStreamWriter(cs);
//Andwritesomedata
sw.WriteLine("'Twasbrillig,andtheslithytoves");
sw.WriteLine("Didgyreandgimbleinthewabe.");
sw.Flush();
sw.Close();
//savethekeyandIVforfutureuse
FileStreamfsKeyOut=File.Create(@"c:\\temp\encrypted.key");
//useaBinaryWritertowriteformatteddatatothefile
BinaryWriterbw=newBinaryWriter(fsKeyOut);
//writedatatothefile
bw.Write(tdes.Key);
bw.Write(tdes.IV);
//flushandclose
bw.Flush();
bw.Close();
}
}
解密代码如下
usingSystem;
usingSystem.IO;
usingSystem.Security.Cryptography;
publicclassExample19_10
{
publicstaticvoidMain()
{
//Createanewcryptoprovider
TripleDESCryptoServiceProvidertdes=
newTripleDESCryptoServiceProvider();
//openthefilecontainingthekeyandIV
FileStreamfsKeyIn=File.OpenRead(@"c:\temp\encrypted.key");
//useaBinaryReadertoreadformatteddatafromthefile
BinaryReaderbr=newBinaryReader(fsKeyIn);
//readdatafromthefileandcloseit
tdes.Key=br.ReadBytes(24);
tdes.IV=br.ReadBytes(8);
//Opentheencryptedfile
FileStreamfsIn=File.OpenRead(@"c:\\temp\\encrypted.txt");
//Createacryptostreamtodecryptfromthefilestream
CryptoStreamcs=newCryptoStream(fsIn,tdes.CreateDecryptor(),
CryptoStreamMode.Read);
//CreateaStreamReadertoformattheinput
StreamReadersr=newStreamReader(cs);
//Anddecryptthedata
Console.WriteLine(sr.ReadToEnd());
sr.Close();
}
}
以上所述就是本文的全部内容了,希望大家能够喜欢。
热门推荐
7 简短的二胎祝福语
10 简短霸气女儿生日 祝福语
11 祝福语高考小众诗句简短
12 元旦祝福语20秒简短
13 老师过年祝福语大全 简短
14 一生祝福语简短
15 产检祝福语简短霸气
16 朋友店开张祝福语简短
17 生日爱情祝福语大全简短
18 朋友女儿生日祝福语 简短