13 Haz

C# Stream Encryption and Decryption With Multi Algorithm Support

Short information about encryption:
There are many encryption algorithm. They are divided into two as symetric and asymmetric. Symmetric encryption and asymmetric encryption are performed using different processes. Symmetric encryption is performed on streams and is therefore useful to encrypt large amounts of data. Asymmetric encryption is performed on a small number of bytes and is therefore useful only for small amounts of data.

For more information:
http://msdn.microsoft.com/en-us/library/as0w18af%28v=vs.110%29.aspx

This example shows how to encrypt a string or stream data in .NET Framework.
You can encrypt/decrypt all data types(string, file etc.) using sample class.

Usage:

            string plainText = "This is a plain text.";
            CryptoService cryptoService = new CryptoService();
            byte[] data = Encoding.Unicode.GetBytes(plainText);
            byte[] key = Encoding.Unicode.GetBytes("key");
            byte[] cipherData = cryptoService.Encrypt(data, key);

            byte[] decryptedData = cryptoService.Decrypt(cipherData, key);
            string againPlainText = Encoding.Unicode.GetString(decryptedData);

Crypto Code:

    public class CryptoService
    {
        private CipherMode _cipherMode = CipherMode.CFB;
        private PaddingMode _paddingMode = PaddingMode.PKCS7;

        private static readonly byte[] _salt = new byte[] { 0x25, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x12, 0x3c };

        private EncryptionAlgorithm _algorithm = EncryptionAlgorithm.AES;
        public EncryptionAlgorithm Algorithm
        {
            get { return _algorithm; }
            set { _algorithm = value; }
        }
        
        public Stream Encrypt(Stream streamToEncrypt, byte[] key)
        {
            SymmetricAlgorithm algorithm = null;
            if (_algorithm == EncryptionAlgorithm.TripleDES)
                algorithm = new TripleDESCryptoServiceProvider();
            else if (_algorithm == EncryptionAlgorithm.AES)
                algorithm = new RijndaelManaged();
            else
                throw new ApplicationException("Unexpected algorithm type!");

            algorithm.Mode = _cipherMode;
            algorithm.Padding = _paddingMode;

            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(key, _salt, 100);
            algorithm.Key = rfc.GetBytes(algorithm.KeySize / 8);
            algorithm.IV = rfc.GetBytes(algorithm.BlockSize / 8);

            try
            {
                ICryptoTransform encryptor = algorithm.CreateEncryptor();
                using (CryptoStream cryptoStream = new CryptoStream(streamToEncrypt, encryptor, CryptoStreamMode.Read))
                {
                    MemoryStream ms = new MemoryStream();
                    CopyStream(cryptoStream, ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    return ms;
                }
            }
            finally
            {
                algorithm.Clear();
            }
        }

        public Stream Decrypt(Stream streamToDecrypt, byte[] key)
        {
            SymmetricAlgorithm algorithm = null;
            if (_algorithm == EncryptionAlgorithm.TripleDES)
                algorithm = new TripleDESCryptoServiceProvider();
            else if (_algorithm == EncryptionAlgorithm.AES)
                algorithm = new RijndaelManaged();
            else
                throw new ApplicationException("Unexpected algorithm type!");

            algorithm.Mode = _cipherMode;
            algorithm.Padding = _paddingMode;

            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(key, _salt, 100);
            algorithm.Key = rfc.GetBytes(algorithm.KeySize / 8);
            algorithm.IV = rfc.GetBytes(algorithm.BlockSize / 8);

            try
            {
                ICryptoTransform decryptor = algorithm.CreateDecryptor();
                using (CryptoStream cryptoStream = new CryptoStream(streamToDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    MemoryStream ms = new MemoryStream();
                    CopyStream(cryptoStream, ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    return ms;
                }
            }
            finally
            {
                algorithm.Clear();
            }
        }

        public byte[] Encrypt(byte[] dataToEncrypt, byte[] key)
        {
            MemoryStream ms = new MemoryStream(dataToEncrypt);
            Stream res = Encrypt(ms, key);
            if (res != null)
            {
                byte[] tmp = new byte[res.Length];
                res.Read(tmp, 0, tmp.Length);
                return tmp;
            }

            return null;
        }

        public byte[] Decrypt(byte[] dataToDecrypt, byte[] key)
        {
            MemoryStream ms = new MemoryStream(dataToDecrypt);
            Stream res = Decrypt(ms, key);
            if (res != null)
            {
                byte[] tmp = new byte[res.Length];
                res.Read(tmp, 0, tmp.Length);
                return tmp;
            }

            return null;
        }

        public void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
            }
        }
    }

    public enum EncryptionAlgorithm
    {
        TripleDES,
        AES,
    }
13 Haz

C# IStream Implementation and IStream Wrapper Class Example

See example/usage below for istream implementation and wrapper. Attachment has two c# files includes MamagedIStream and IStreamWrapper class.

Usage IStreamWrapper and ManagedIStream:

            
            //IStreamWrapper  usage
            IStream iStream = null; // set a new instance
            IStreamWrapper sw = new IStreamWrapper(iStream);
            byte[] data = new byte[1];
            sw.Read(data, 0, 1);


            //ManagedIStream usage
            Stream ms = null; // set a new stream instance
            ManagedIStream managedIStream = new ManagedIStream(ms); // ManagedIStream class implements IStream interface.

Download Files:
CSharpExamples-Managed IStream and IStreamWrapper.RAR

13 Haz

C# Copy Stream Examples

Best ways to copy between two stream are like below. There is no special method for .NET Framework 3.5 and before. We writes a sample method using Read and Write methods in Stream class. But .NET Framework 4.0 and later, some methods are added to framework api.

        /// 
        /// code examples for .NET 3.5 and before
        /// 
        /// 
        /// 
        public static void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
            }
        }

From .NET 4.0 on, there’s is the Stream.CopyTo method

            Stream inputStream = null;
            Stream outputStream = null;
            inputStream.CopyTo(outputStream);
13 Haz

C# Get File List From Directory

Directory.GetFiles in System.IO namespace returns a string array contains the full paths of all the files contained inside the specified directory. This method can be used.
Sample directory and file structure is like below:
“C:\TestDirectory\Files\file1.png”
“C:\TestDirectory\Files\file2.avi”
“C:\TestDirectory\Files\file3.jpg”
“C:\TestDirectory\Files\SubFolder\file4.jpg”
“C:\TestDirectory\Files\SubFolder\file5.avi”

This example writes the name of files from a directory.

            string[] filePaths = Directory.GetFiles(@"C:\TestDirectory\Files\");
            foreach (string file in filePaths)
                Console.WriteLine(file);
            
            // Result:
            // "C:\TestDirectory\Files\file1.png"
            // "C:\TestDirectory\Files\file2.avi"
            // "C:\TestDirectory\Files\file3.jpg"

Also you can add search pattern. Second parametre is search string to match against the names of files in path. The parameter cannot end in two periods (“..”) or contain two periods (“..”) followed by System.IO.Path.DirectorySeparatorChar or System.IO.Path.AltDirectorySeparatorChar, nor can it contain any of the characters in System.IO.Path.InvalidPathChars.

            string[] filePaths = Directory.GetFiles(@"C:\TestDirectory\Files\", "*.avi");
            foreach (string file in filePaths)
                Console.WriteLine(file);

            // Result:
            // "C:\TestDirectory\Files\file2.avi"

“Directory.GetFiles” method includes only the current directory in a search as default. If you want to search all subdirectories, you can set the search option as third parameter(SearchOption.AllDirectories).

            string[] filePaths = Directory.GetFiles(@"C:\TestDirectory\Files\", "*.avi", SearchOption.AllDirectories);
            foreach (string file in filePaths)
                Console.WriteLine(file);
            
            // Result:
            // "C:\TestDirectory\Files\file2.avi"
            // "C:\TestDirectory\Files\SubFolder\file5.avi"

For .NET Framework 4.0 and layer, you can use this example.

            //For .NET 4.0 and later,
            var filePaths = Directory.EnumerateFiles(@"C:\TestDirectory\Files\").Where(s => s.EndsWith(".avi"));
            foreach (string file in filePaths)
                Console.WriteLine(file);

            // Result:
            // "C:\TestDirectory\Files\file2.avi"
13 Haz

C# Send an Email Using Outlook Program

To send an email using outlook program, we need to add a reference to the dynamic link library for Outlook which is called Microsoft.Office.Interop.Outlook.dll. To do this, firstly go to your solution explorer and click on add a reference. Then, add Microsoft.Office.Interop.Outlook.dll.

Sample code and usage are below.

Usage:

            //using MsOutlook = Microsoft.Office.Interop.Outlook;
            //You must add using statement.

            string[] attachFiles = new string[] { 
                @"C:\test.txt"
            };
            SendMailWithOutlook("Subject1", "This is an example.", "test@csharpexample.com", attachFiles, MailSendType.SendDirect);

Code:

        public enum MailSendType
        {
            SendDirect = 0,
            ShowModal = 1,
            ShowModeless = 2,
        }

        public bool SendMailWithOutlook(string subject, string htmlBody, string recipients, string[] filePaths, MailSendType sendType)
        {
            try
            {
                // create the outlook application.
                MsOutlook.Application outlookApp = new MsOutlook.Application();
                if (outlookApp == null)
                    return false;

                // create a new mail item.
                MsOutlook.MailItem mail = (MsOutlook.MailItem)outlookApp.CreateItem(MsOutlook.OlItemType.olMailItem);

                // set html body. 
                // add the body of the email
                mail.HTMLBody = htmlBody;

                //Add attachments.
                if (filePaths != null)
                {
                    foreach (string file in filePaths)
                    {
                        //attach the file
                        MsOutlook.Attachment oAttach = mail.Attachments.Add(file);
                    }
                }

                mail.Subject = subject;
                mail.To = recipients;
                
                if (sendType == MailSendType.SendDirect)
                    mail.Send();
                else if (sendType == MailSendType.ShowModal)
                    mail.Display(true);
                else if (sendType == MailSendType.ShowModeless)
                    mail.Display(false);

                mail = null;
                outlookApp = null;
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }