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();
}
}
以上所述就是本文的全部内容了,希望大家能够喜欢。
热门推荐
2 成都训练狗狗
3 怎么训练小狗狗
4 训练狗狗软件
5 如何训练狗狗拉屎
9 狗狗负重训练
10 狗狗多大可以训练大小便
11 怎么训练狗狗萨摩耶
12 狗狗训练书
13 鞍山狗狗训练
14 训练狗狗用品
15 怎样才能训练狗狗听话
16 狗狗如何训练大小便
17 怎样训练狗狗睡狗窝
18 训练狗狗工具