background image

  下面是加密和解密一个文本文件的源程序片断:

namespace com.billdawson.crypto
{
class TextFileCrypt
{
public static void Main(string[] args)
{
string file = args[0];
string tempfile = Path.GetTempFileName();
//打开指定的文件
FileStream fsIn = File.Open(file,FileMode.Open,
FileAccess.Read);
FileStream fsOut = File.Open(tempfile, FileMode.Open,
FileAccess.Write);
//定义对称算法对象实例和接口
SymmetricAlgorithm symm = new RijndaelManaged();
ICryptoTransform transform = symm.CreateEncryptor();
CryptoStream cstream = new CryptoStream(fsOut,transform,
ryptoStreamMode.Write);

BinaryReader br = new BinaryReader(fsIn);
// 读取源文件到 cryptostream 
cstream.Write(br.ReadBytes((int)fsIn.Length),0,(int)fsIn.Length);
cstream.FlushFinalBlock();
cstream.Close();
fsIn.Close();
fsOut.Close();

Console.WriteLine("created encrypted file {0}", tempfile);
Console.WriteLine("will now decrypt and show contents");

// 反向操作--解密刚才加密的临时文件
fsIn = File.Open(tempfile,FileMode.Open,FileAccess.Read);
transform = symm.CreateDecryptor();
cstream = new CryptoStream(fsIn,transform,
CryptoStreamMode.Read);

StreamReader sr = new StreamReader(cstream);
Console.WriteLine("decrypted file text: " + sr.ReadToEnd());
fsIn.Close();