Create and use a DESCryptoServiceProvider object to encrypt and decrypt data in a file. : DES « Security « C# / CSharp Tutorial






using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

class DESCSPSample
{
    static void Main()
    {
        DESCryptoServiceProvider DESalg = new DESCryptoServiceProvider();
        string sData = "this is a test.";
        string FileName = "CText.txt";
        EncryptTextToFile(sData, FileName, DESalg.Key, DESalg.IV);
        string Final = DecryptTextFromFile(FileName, DESalg.Key, DESalg.IV);
        Console.WriteLine(Final);
    }
    public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV)
    {
        FileStream fStream = File.Open(FileName,FileMode.OpenOrCreate);
        CryptoStream cStream = new CryptoStream(fStream,new DESCryptoServiceProvider().CreateEncryptor(Key,IV), 
                CryptoStreamMode.Write); 

        StreamWriter sWriter = new StreamWriter(cStream);
        sWriter.WriteLine(Data);
        sWriter.Close();
        cStream.Close();
        fStream.Close();
    }
    public static string DecryptTextFromFile(String FileName, byte[] Key, byte[] IV)
    {
        FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);
        CryptoStream cStream = new CryptoStream(fStream,new DESCryptoServiceProvider().CreateDecryptor(Key,IV), 
                CryptoStreamMode.Read); 
        StreamReader sReader = new StreamReader(cStream);
        string val = sReader.ReadLine();
        sReader.Close();
        cStream.Close();
        fStream.Close();
        return val;
    }
}








35.13.DES
35.13.1.Secret Key Cryptography: DES
35.13.2.Secret Key Cryptography: TripleDES
35.13.3.Create and use a DESCryptoServiceProvider object to encrypt and decrypt data in memory.
35.13.4.Create and use a DESCryptoServiceProvider object to encrypt and decrypt data in a file.