Wednesday 22 August 2012

Cryptography using Triple DES Algorithm in C#


Triple DES Algorithm:

                  Represents the base class for Triple Data Encryption Standard algorithms from which all TripleDES implementations must derive.





using System.Security.Cryptography;    

Encryption:


    public byte[] Encryption(string PlainText, string key)
        {
            try
            {
                TripleDES des = CreateDES(key);

                ICryptoTransform ct = des.CreateEncryptor();

                byte[] input = Encoding.Unicode.GetBytes(PlainText);

                return ct.TransformFinalBlock(input, 0, input.Length);
            }
            catch
            {
                return null;
            }
        }

Decryption:


        public string Decryption(string CypherText, string key)
        {
            try
            {
                byte[] b = Convert.FromBase64String(CypherText);

                TripleDES des = CreateDES(key);
                ICryptoTransform ct = des.CreateDecryptor();
                byte[] output = ct.TransformFinalBlock(b, 0, b.Length);
                return Encoding.Unicode.GetString(output);
            }
            catch
            {
                return null;
            }
        }

 TripleDES Class:



        static TripleDES CreateDES(string key)
        {
            try
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                TripleDES des = new TripleDESCryptoServiceProvider();
                des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key));
                des.IV = new byte[des.BlockSize / 8];
                return des;
            }
            catch
            {
                return null;
            }
        }


Other Class in C#:






No comments:

Post a Comment