爱自由飞翔 發表於 2008-10-8 19:02:40

C#的加密与解密

using System;<br />

using System.IO;<br />

using System.Security.Cryptography;<br />

using System.Text;<br />

class FileEncrypt {<br />

public static Byte[] ConvertStringToByteArray(String s)<br />

{<br />

return (new UnicodeEncoding()).GetBytes(s);<br />

}<br />

public static void Main()<br />

{<br />

//创建文件流<br />

FileStream fs = new FileStream(&quot;EncryptedFile.txt&quot;,FileMode.Create,FileAccess.Write);<br />

Console.WriteLine(&quot;输入一些要存储在加密文件中的文本::&quot;);<br />

String strinput = Console.ReadLine();<br />

Byte[] bytearrayinput=ConvertStringToByteArray(strinput);<br />

//具有随机密钥的 DES 实例<br />

DESCryptoServiceProvider des = new DESCryptoServiceProvider();<br />

//从此实例创建 DES 加密器<br />

ICryptoTransform desencrypt = des.CreateEncryptor();<br />

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

CryptoStream cryptostream = new CryptoStream(fs,desencrypt,CryptoStreamMode.Write);<br />

//写出 DES 加密文件<br />

cryptostream.Write(bytearrayinput,0,bytearrayinput.Length);<br />

cryptostream.Close();<br />

//创建文件流以读回加密文件<br />

FileStream fsread = new FileStream(&quot;EncryptedFile.txt&quot;,FileMode.Open,FileAccess.Read);<br />

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

ICryptoTransform desdecrypt = des.CreateDecryptor();<br />

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

CryptoStream cryptostreamDecr = new CryptoStream(fsread,desdecrypt,CryptoStreamMode.Read);<br />

//输出已解密文件的内容<br />

Console.WriteLine( (new StreamReader(cryptostreamDecr, new UnicodeEncoding())).ReadToEnd() );<br />

Console.WriteLine ();<br />

Console.WriteLine (&quot;按 Enter 键继续...&quot;);<br />

Console.ReadLine();<br />

}<br />

}



<br />
頁: [1]
查看完整版本: C#的加密与解密