字符串加密写入文本文件(01)
该方法经过测试,并应用到项目了。
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace TBQDLKW { public class FileEncryptDecrypt { /// <summary> /// 加密字符【长度必须为8】 /// </summary> private static string _Key = "TBQDLKSW"; /// <summary> /// 将密钥加密写入到文件 /// </summary> /// <param name="sOutputFilename">文件路径</param> /// <param name="content">文件内容</param> /// <param name="sKey">密钥</param> private static void EncryptFile(string sOutputFilename, string content, string sKey) { using (FileStream fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write)) { using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = Encoding.ASCII.GetBytes(sKey); des.IV = Encoding.ASCII.GetBytes(sKey); ICryptoTransform desencrypt = des.CreateEncryptor(); using (CryptoStream cryptostream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write)) { byte[] fsInput = Encoding.UTF8.GetBytes(content); cryptostream.Write(fsInput, 0, fsInput.Length); cryptostream.Close(); fsEncrypted.Close(); } } } } /// <summary> /// 打开密钥文件 /// </summary> private static string DecryptFile(string sInputFilename, string sKey) { using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = Encoding.ASCII.GetBytes(sKey); des.IV = Encoding.ASCII.GetBytes(sKey); using (FileStream fsread = new System.IO.FileStream(sInputFilename, FileMode.Open, FileAccess.Read)) { ICryptoTransform desdecrypt = des.CreateDecryptor(); using (CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read)) { using (StreamReader read = new StreamReader(cryptostreamDecr, Encoding.UTF8)) { string reft = read.ReadToEnd(); fsread.Flush(); fsread.Close(); return reft; } } } } } /// <summary> /// 加密文件 /// </summary> /// <param name="filename">文件存放路径</param> /// <param name="content">加密内容</param> public static void Encrypt(string filename, string content) { try { EncryptFile(filename, content, _Key); } catch (Exception ex) { } } /// <summary> /// 解密文件 /// </summary> /// <param name="filename">打开文件路径</param> /// <returns>返回加密文件的内容</returns> public static bool Decrypt(string filename, out string content) { content = null; try { content = DecryptFile(filename, _Key); return true; } catch (Exception ex) { content = "文件不正确!"; return false; } } } }