Create and use a DESCryptoServiceProvider object to encrypt and decrypt data in memory. : 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.";
        byte[] Data = EncryptTextToMemory(sData, DESalg.Key, DESalg.IV);
        string Final = DecryptTextFromMemory(Data, DESalg.Key, DESalg.IV);
        Console.WriteLine(Final);
    }
    public static byte[] EncryptTextToMemory(string Data,  byte[] Key, byte[] IV)
    {
        MemoryStream mStream = new MemoryStream();
        CryptoStream cStream = new CryptoStream(mStream,new DESCryptoServiceProvider().CreateEncryptor(Key, IV), 
                CryptoStreamMode.Write);
        byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);
        cStream.Write(toEncrypt, 0, toEncrypt.Length);
        cStream.FlushFinalBlock();
        byte[] ret = mStream.ToArray();
        cStream.Close();
        mStream.Close();
        return ret;
    }

    public static string DecryptTextFromMemory(byte[] Data,  byte[] Key, byte[] IV)
    {
        MemoryStream msDecrypt = new MemoryStream(Data);
        CryptoStream csDecrypt = new CryptoStream(msDecrypt,new DESCryptoServiceProvider().CreateDecryptor(Key, IV), 
                CryptoStreamMode.Read);

        byte[] fromEncrypt = new byte[Data.Length];
        csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
        return new ASCIIEncoding().GetString(fromEncrypt);
    }
}








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.