C#實現(xiàn)對文件進行加密解密的方法
更新時間:2015年04月08日 12:25:14 作者:heishui
這篇文章主要介紹了C#實現(xiàn)對文件進行加密解密的方法,涉及C#加密與解密的技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#實現(xiàn)對文件進行加密解密的方法。分享給大家供大家參考。具體如下:
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#程序設(shè)計有所幫助。
相關(guān)文章
使用GetInvalidFileNameCharts生成文件名
這篇文章主要介紹了一個很實用的函數(shù)Path.GetInvalidFileNameCharts(),他可以很方便的生成一個有效的文件名稱2014-01-01

