Baran Topal

Baran Topal


May 2024
M T W T F S S
« Feb    
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories


CryptoServices in .NET: 3DES

baranbaran

Well, this is a followup of the post

This is the .NET Realm implementation. Note there are 4 other parts to fulfill this cryptoservices completely. Check the above link’s requirements, yet, this is also a standalone module if you implement this as a console library.

Triple DES is famous for weakness that you can brute force. Yes, it’s true but let me say, it’s really plain to use this in CBC. You don’t have to give an input file, rather a byte buffer if you like.

Following is the code:



/* 
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Company: -								 			 *            
 * Assignment: Cyclic Redundancy Check + 3DES + EF + WCF	                                 *
 * Deadline: -                           	 						 *
 * Programmer: Baran Topal                   							 *
 * Solution: Crypto					 					 *
 * Project Name: 3DES          	        	 						 *
 * File name: EncDes.cs                       							 *
 *                                           							 *      
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *	                                                                                         *
 *  LICENSE: This source file is subject to have the protection of GNU General                   *
 *	Public License. You can distribute the code freely but storing this license information. *
 *	Contact Baran Topal if you have any questions. barantopal@barantopal.com                 *
 *	                                                                                         *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 */

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

namespace _3DES
{
    public class EncDec
    {
        private static byte[] randomBytes;

        // Byte randomization        
        public EncDec()
        {
            byte[] array = new byte[8];
            Random random = new Random();
            random.NextBytes(array);

            // Test
            foreach (byte value in array)
            {
                Console.WriteLine(value);
                Console.Write(' ');
            }
            Console.WriteLine();
            randomBytes = array;
        }

        // Encrypt the clear byte data with key and IV       
        public static byte[] Encrypt(byte[] clearData, byte[] key, byte[] IV)
        {
            MemoryStream ms = new MemoryStream();


            TripleDES alg = TripleDES.Create();

            alg.Key = key;
            alg.IV = IV;
            using (CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(clearData, 0, clearData.Length);
            }

            byte[] encryptedData = ms.ToArray();
            return encryptedData;
        }

        // Encrypt the clear string data with a password        
        public static string Encrypt(string clearText, string trivia)
        {
            byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(trivia, randomBytes);

            byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(8), pdb.GetBytes(8));

            return Convert.ToBase64String(encryptedData);
        }

        // Encrypt the clear byte data with a password        
        public static byte[] Encrypt(byte[] clearData, string trivia)
        {
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(trivia, randomBytes);
            return Encrypt(clearData, pdb.GetBytes(8), pdb.GetBytes(8));
        }

        // Encrypt the file input data with a password to a file output        
        public static void Encrpyt(string fileIn, string fileOut, string trivia)
        {
            FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
            FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(trivia, randomBytes);


            TripleDES alg = TripleDES.Create();
            alg.Key = pdb.GetBytes(alg.KeySize / 8);
            alg.IV = pdb.GetBytes(8);

            using (CryptoStream cs = new CryptoStream(fsOut, alg.CreateEncryptor(), CryptoStreamMode.Write))
            {
                int bufferLen = 4096;
                byte[] buffer = new byte[bufferLen];

                int bytesRead;

                do
                {
                    bytesRead = fsIn.Read(buffer, 0, bufferLen);
                    cs.Write(buffer, 0, bytesRead);
                } while (bytesRead != 0);
            }
        }

        // Similar with above definitions but Decrypt        
        public static byte[] Decrypt(byte[] cipherData, byte[] key, byte[] IV)
        {
            MemoryStream ms = new MemoryStream();
            TripleDES alg = TripleDES.Create();

            alg.Key = key;
            alg.IV = IV;

            using (CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(cipherData, 0, cipherData.Length);
            }

            byte[] decryptedData = ms.ToArray();
            return decryptedData;
        }


        public static string Decrypt(string cipherText, string trivia)
        {
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(trivia, randomBytes);

            byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(8), pdb.GetBytes(8));
            return System.Text.Encoding.Unicode.GetString(decryptedData);
        }

        public static byte[] Decrypt(byte[] cipherData, string trivia)
        {
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(trivia, randomBytes);
            return Decrypt(cipherData, pdb.GetBytes(8), pdb.GetBytes(8));
        }

        public static void Decrypt(string fileIn, string fileOut, string trivia)
        {
            FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
            FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(trivia, randomBytes);
            TripleDES alg = TripleDES.Create();

            alg.Key = pdb.GetBytes(alg.KeySize / 8);
            alg.IV = pdb.GetBytes(8);

            using (CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), CryptoStreamMode.Write))
            {
                int bufferLen = 4096;
                byte[] buffer = new byte[bufferLen];
                int bytesRead;

                do
                {
                    bytesRead = fsIn.Read(buffer, 0, bufferLen);
                    cs.Write(buffer, 0, bytesRead);

                } while (bytesRead != 0);
            }
        }
    }
}


This is a standalone module actually. Feel free to run:


/* 
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
 * Company: -								 			 *            
 * Assignment: Cyclic Redundancy Check + 3DES + EF + WCF	                                 *
 * Deadline: -                           	 						 *
 * Programmer: Baran Topal                   							 *
 * Solution: Crypto					 					 *
 * Project Name: 3DES          	        	 						 *
 * File name: Program.cs                       							 *
 *                                           							 *      
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *	                                                                                         *
 *  LICENSE: This source file is subject to have the protection of GNU General                   *
 *	Public License. You can distribute the code freely but storing this license information. *
 *	Contact Baran Topal if you have any questions. barantopal@barantopal.com                 *
 *	                                                                                         *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _3DES
{
    // DLL
    class Program
    {
        static void Main(string[] args)
        {
            // Test data
            EncDec e = new EncDec();
            EncDec.Encrpyt("loremipsum.txt", "encrypted.enc", "1234-4567-8910-2345");
            EncDec.Decrypt("encrypted.enc", "decrypted.dec", "1234-4567-8910-2345");
        }
    }
}

loremipsum.txt content is as follows:


Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas imperdiet venenatis sodales. Nunc elementum scelerisque nibh, nec pellentesque lacus hendrerit sit amet. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cras luctus euismod augue, vitae pulvinar est feugiat vitae. Nunc ultricies facilisis mi sed commodo. Aliquam erat volutpat. Etiam id libero nunc. Morbi porttitor porta urna at facilisis.
 
Quisque at mauris quşam, in tempor odio. Aenean tempus enim quis velit consequat ac molestie sapien malesuada. Fusce mauris tellus, bibendum in scelerisque sit amet, tristique at lectus. Morbi posuere magna sed turpis lacinia ut consequat leo pellentesque. Sed sem orci, dictum non mattis quis, lobortis in diam. Vivamus sed erat ac eros euismod adipiscing eu et dolor. Nulla fringilla erat eu quam fringilla et dapibus quam imperdiet. Nullam a tempus leo. Suspendisse in justo turpis, nec convallis nisl. Donec vulputate, odio viverra euismod placerat, massa risus bibendum mauris, vestibulum fermentum justo metus quis nisl.

Comments 0
There are currently no comments.