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("EncryptedFile.txt",FileMode.Create,FileAccess.Write);<br />
Console.WriteLine("输入一些要存储在加密文件中的文本::");<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("EncryptedFile.txt",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 ("按 Enter 键继续...");<br />
Console.ReadLine();<br />
}<br />
}
<br />
頁:
[1]