DES Encrypt Data - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:DES

Description

DES Encrypt Data

Demo Code


using System.Globalization;
using System.Text;
using System.Security.Cryptography;
using System.IO;//  w w  w. j a  v a  2s.  c  o m
using System.Web;
using System.Linq;
using System.Collections.Generic;
using System;

public class Main{
        public static void EncryptData(Stream fin, Stream fout,
            Byte[] desKey, Byte[] desIV)
        {            
            Byte[] bin = new Byte[4096];    //This is intermediate storage for the encryption.
            long rdlen = 0; //This is the total number of bytes written.
            long totlen = fin.Length; //Total length of the input file.
            int len; //This is the number of bytes to be written at a time.
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);

            //Read from the input file, then encrypt and write to the output file.
            while (rdlen < totlen)
            {
                len = fin.Read(bin, 0, 4096);
                encStream.Write(bin, 0, len);
                rdlen = Convert.ToInt32(rdlen + len / des.BlockSize * des.BlockSize);
            }

            encStream.FlushFinalBlock();
        }
}

Related Tutorials