C#加密与解密

发表于:2007-06-21来源:作者:点击数: 标签:
using System; using System.IO; using System.Security.Cryptography; using System.Text; class FileEncrypt { public static Byte[] ConvertStringToByteArray(String s) { return (new UnicodeEncoding()).GetBytes(s); } public static void Main() { /

   
  using System;

using System.IO;

using System.Security.Cryptography;

using System.Text;

class FileEncrypt {

public static Byte[] ConvertStringToByteArray(String s)

{

return (new UnicodeEncoding()).GetBytes(s);

}

public static void Main()

{

//创建文件流

FileStream fs = new FileStream("EncryptedFile.txt",FileMode.Create,FileAclearcase/" target="_blank" >ccess.Write);

Console.WriteLine("输入一些要存储在加密文件中的文本::");

String strinput = Console.ReadLine();

Byte[] bytearrayinput=ConvertStringToByteArray(strinput);

//具有随机密钥的 DES 实例

DESCryptoServiceProvider des = new DESCryptoServiceProvider();

//从此实例创建 DES 加密器

ICryptoTransform desencrypt = des.CreateEncryptor();

//创建使用 des 加密转换文件流的加密流

CryptoStream cryptostream = new CryptoStream(fs,desencrypt,CryptoStreamMode.Write);

//写出 DES 加密文件

cryptostream.Write(bytearrayinput,0,bytearrayinput.Length);

cryptostream.Close();

//创建文件流以读回加密文件

FileStream fsread = new FileStream("EncryptedFile.txt",FileMode.Open,FileAccess.Read);

//从此 des 实例创建 DES 解密器

ICryptoTransform desdecrypt = des.CreateDecryptor();

//创建加密流集合以便对传入的字节进行读取并执行 des 解密转换

CryptoStream cryptostreamDecr = new CryptoStream(fsread,desdecrypt,CryptoStreamMode.Read);

//输出已解密文件的内容

Console.WriteLine( (new StreamReader(cryptostreamDecr, new UnicodeEncoding())).ReadToEnd() );

Console.WriteLine ();

Console.WriteLine ("按 Enter 键继续...");

Console.ReadLine();

}

}

原文转自:http://www.ltesting.net