/// <summary> /// 对文件内容进行DES加密 /// </summary> /// <param name="sourceFile">待加密的文件绝对路径</param> /// <param name="destFile">加密后的文件保存的绝对路径</param> public void EncryptFile(string sourceFile, string destFile,string key) { if (!File.Exists(sourceFile)) throw new FileNotFoundException("指定的文件路径不存在!", sourceFile); byte[] btKey = Encoding.Default.GetBytes(key); byte[] btIV = Encoding.Default.GetBytes(key); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] btFile = File.ReadAllBytes(sourceFile); using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write)) { try { using (CryptoStream cs = new CryptoStream(fs, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write)) { cs.Write(btFile, 0, btFile.Length); cs.FlushFinalBlock(); } } catch { throw; } finally { fs.Close(); } } } /// <summary> /// 对文件内容进行DES解密 /// </summary> /// <param name="sourceFile">待解密的文件绝对路径</param> /// <param name="destFile">解密后的文件保存的绝对路径</param> public void DecryptFile(string sourceFile, string destFile,string key) { if (!File.Exists(sourceFile)) throw new FileNotFoundException("指定的文件路径不存在!", sourceFile); byte[] btKey = Encoding.Default.GetBytes(key); byte[] btIV = Encoding.Default.GetBytes(key); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] btFile = File.ReadAllBytes(sourceFile); using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write)) { try { using (CryptoStream cs = new CryptoStream(fs, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write)) { cs.Write(btFile, 0, btFile.Length); cs.FlushFinalBlock(); } } catch { throw; } finally { fs.Close(); } } }