using System.IO; using System.Security.Cryptography; public void EncryptTextToFile(string para_text, string para_path, byte[] para_key, byte[] para_iv) ... public string DecryptTextFromFile(string para_path, byte[] para_key, byte[] para_iv) ...
using System.IO; using System.Security.Cryptography; public void EncryptTextToFile(string para_text, string para_path, byte[] para_key, byte[] para_iv) { try { // Create or open the specified file using (FileStream _fStream = File.Open(para_path, FileMode.Create)) // Create a new DES object using (DES _des = DES.Create()) // Create a DES encryptor from the key and IV using (ICryptoTransform _encryptor = _des.CreateEncryptor(para_key, para_iv)) // Create a CryptoStream using the FileStream and encryptor using (var cStream = new CryptoStream(_fStream, _encryptor, CryptoStreamMode.Write)) { // Convert the provided string to a byte array byte[] _toEncrypt = Encoding.UTF8.GetBytes(para_text); // Write the byte array to the crypto stream cStream.Write(_toEncrypt, 0, _toEncrypt.Length); } } catch (CryptographicException ex) { MessageBox.Show("An encryption to file error occurred: {0}", ex.Message); throw; } } public string DecryptTextFromFile(string para_path, byte[] para_key, byte[] para_iv) { try { // Open the specified file using (FileStream _fStream = File.OpenRead(para_path)) // Create a new DES object. using (DES _des = DES.Create()) // Create a DES decryptor from the key and IV using (ICryptoTransform _decryptor = _des.CreateDecryptor(para_key, para_iv)) // Create a CryptoStream using the FileStream and decryptor using (var _cStream = new CryptoStream(_fStream, _decryptor, CryptoStreamMode.Read)) // Create a StreamReader to turn the bytes back into text using (StreamReader reader = new StreamReader(_cStream, Encoding.UTF8)) { // Read back all of the text from the StreamReader, which receives // the decrypted bytes from the CryptoStream, which receives the // encrypted bytes from the FileStream. return reader.ReadToEnd(); } } catch (CryptographicException ex) { MessageBox.Show("A decryption from file error occurred: {0}", ex.Message); throw; } }