Thursday 2 June 2016

Encryption and decryption using DESCryptoServiceProvider in C#

If you want to encrypt and decrypt text using FIPS complaint algorithm just use DESCryptoServiceProvider SymmetricAlgorithm for framework 2.0 and above.



 public class _Security
    {
        public static SymmetricAlgorithm objCrptoService = new DESCryptoServiceProvider();
        //You can modif the the tempIV
        static string tempIV = "1b46123aaed34e869af8";


        public static string EncryptString(string sourceText, string key)
        {
            try
            {
                // Create a memory stream 
                MemoryStream objMemStream = new MemoryStream();

                //Set the legal keys and initialization verctors
                objCrptoService.Key = GetLegalsecretKey(key);
                objCrptoService.IV = GetLegalIV();


                ICryptoTransform desencrypt = objCrptoService.CreateEncryptor();
                CryptoStream cryptostream = new CryptoStream(objMemStream, desencrypt, CryptoStreamMode.Write);
                //CryptoStream objCryptStream = new CryptoStream(objMemStream, objCrptoService.CreateEncryptor(), CryptoStreamMode.Write);

                StreamWriter objStreamWriter = new StreamWriter(cryptostream);
 
                // Write the sourceText to the memroy stream.
                objStreamWriter.WriteLine(sourceText);

                // Close the StreamWriter and CryptoStream objects.
                objStreamWriter.Close();
                cryptostream.Close();

                // Get an array of bytes that represents the memory stream.
                byte[] outputBuffer = objMemStream.ToArray();

                // Close the memory stream.
                objMemStream.Close();

                // Return the encrypted byte array.
                string clearText = System.Convert.ToBase64String(outputBuffer);
                clearText = clearText.Replace("+", "$$$$$$");
                clearText = clearText.Replace("/", "@@@@@@");


                return clearText;
            }
            catch (Exception exc)
            {
                return "";
            }


        }


        public static string DecryptString(string encriptedText, string key)
        {

            try
            {
                encriptedText = encriptedText.Replace("$$$$$$", "+");
                encriptedText = encriptedText.Replace("@@@@@@", "/");

                //Convert the text into bytest
                byte[] ecriptedBytes = System.Convert.FromBase64String(encriptedText);

                // Create a memory stream to the passed buffer
                MemoryStream objMemStream = new MemoryStream(ecriptedBytes);

                //Set the legal keys and initialization verctors
                objCrptoService.Key = GetLegalsecretKey(key);
                objCrptoService.IV = GetLegalIV();

                // Create a CryptoStream using the memory stream and the cryptographic service provider  version
                // of the Data Encryption stanadard algorithm key
                CryptoStream objCryptStream = new CryptoStream(objMemStream, objCrptoService.CreateDecryptor(), CryptoStreamMode.Read);

                // Create a StreamReader for reading the stream.
                StreamReader objstreamReader = new StreamReader(objCryptStream);

                // Read the stream as a string.
                string outputText = objstreamReader.ReadLine();

/* 
//Decryption in 4.0 with bad data error solution.
MemoryStream stream = new MemoryStream();
               objCryptStream.CopyTo(stream);
               stream.Position = 0;
               StreamReader R = new StreamReader(stream);
               string outputText = R.ReadToEnd();
*/


                // Close the streams.
                objstreamReader.Close();
                objCryptStream.Close();
                objMemStream.Close();

                return outputText;
            }
            catch(Exception exc)
            {
                return exc.Message;
            }
        }


        private static byte[] GetLegalsecretKey(string secretKey)
        {
            string tempKey = secretKey;
            objCrptoService.GenerateKey();
            byte[] tempBytes = objCrptoService.Key;

            int secretKeyLength = tempBytes.Length;

            if (tempKey.Length > secretKeyLength)
                tempKey = tempKey.Substring(0, secretKeyLength);
            else if (tempKey.Length < secretKeyLength)
                tempKey = tempKey.PadRight(secretKeyLength, ' ');

            return ASCIIEncoding.ASCII.GetBytes(tempKey);
        }


        private static byte[] GetLegalIV()
        {
            objCrptoService.GenerateIV();
            byte[] tempBytes = objCrptoService.IV;
            int len = tempBytes.Length;
            if (tempIV.Length < len)
                tempIV = tempIV.PadRight(len, ' ');
            else
                tempIV = tempIV.Substring(0, len);

            return ASCIIEncoding.ASCII.GetBytes(tempIV);
        }


    }

 


asddfgdfg