Tuesday, March 29, 2022

ASP.NET encryption Encryption.cs

It will store in QueryString folder(App_Code Folder).

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Security.Cryptography;

using System.IO;

using System.Text;


/// <summary>

/// Summary description for Encryption

/// </summary>

public static class Encryption

{

    static private Byte[] m_Key = new Byte[8];

    static private Byte[] m_IV = new Byte[8];


    //You need to replace this key with your own Key.

    private static string strThekey = "5DFE6T@@#$@562";


    /// <summary>

    /// Returns an encrypted string.

    /// </summary>

    public static string Encrypt(String strData)

    {

        string strResult; //Return Result


        //1. String Length cannot exceed 90Kb. Otherwise, buffer will overflow. See point 3 for reasons

        if (strData.Length > 92160)

        {

            strResult = "Error. Data String too large. Keep within 90Kb.";

            return strResult;

        }


        //2. Generate the Keys

        if (!InitKey(strThekey))

        {

            strResult = "Error. Fail to generate key for encryption";

            return strResult;

        }


        //3. Prepare the String

        // The first 5 character of the string is formatted to store the actual length of the data.

        // This is the simplest way to remember to original length of the data, without resorting to complicated computations.

        // If anyone figure a good way to 'remember' the original length to facilite the decryption without having to use additional function parameters, pls let me know.

        strData = String.Format("{0,5:00000}" + strData, strData.Length);



        //4. Encrypt the Data

        byte[] rbData = new byte[strData.Length];

        ASCIIEncoding aEnc = new ASCIIEncoding();

        aEnc.GetBytes(strData, 0, strData.Length, rbData, 0);


        DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();


        ICryptoTransform desEncrypt = descsp.CreateEncryptor(m_Key, m_IV);



        //5. Perpare the streams:

        // mOut is the output stream. 

        // mStream is the input stream.

        // cs is the transformation stream.

        MemoryStream mStream = new MemoryStream(rbData);

        CryptoStream cs = new CryptoStream(mStream, desEncrypt, CryptoStreamMode.Read);

        MemoryStream mOut = new MemoryStream();


        //6. Start performing the encryption

        int bytesRead;

        byte[] output = new byte[1024];

        do

        {

            bytesRead = cs.Read(output, 0, 1024);

            if (bytesRead != 0)

                mOut.Write(output, 0, bytesRead);

        } while (bytesRead > 0);


        //7. Returns the encrypted result after it is base64 encoded

        // In this case, the actual result is converted to base64 so that it can be transported over the HTTP protocol without deformation.

        if (mOut.Length == 0)

            strResult = "";

        else

            strResult = Convert.ToBase64String(mOut.GetBuffer(), 0, (int)mOut.Length);


        return strResult;

    }


    /// <summary>

    /// Returns a decrypted string.

    /// </summary>

    public static string Decrypt(String strData)

    {

        string strResult;


        //1. Generate the Key used for decrypting

        if (!InitKey(strThekey))

        {

            strResult = "Error. Fail to generate key for decryption";

            return strResult;

        }


        //2. Initialize the service provider

        int nReturn = 0;

        DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();

        ICryptoTransform desDecrypt = descsp.CreateDecryptor(m_Key, m_IV);


        //3. Prepare the streams:

        // mOut is the output stream. 

        // cs is the transformation stream.

        MemoryStream mOut = new MemoryStream();

        CryptoStream cs = new CryptoStream(mOut, desDecrypt, CryptoStreamMode.Write);


        //4. Remember to revert the base64 encoding into a byte array to restore the original encrypted data stream

        byte[] bPlain = new byte[strData.Length];

        try

        {

            bPlain = Convert.FromBase64CharArray(strData.ToCharArray(), 0, strData.Length);

        }

        catch (Exception)

        {

            strResult = "Error. Input Data is not base64 encoded.";

            return strResult;

        }


        long lRead = 0;

        long lTotal = strData.Length;


        try

        {

            //5. Perform the actual decryption

            while (lTotal >= lRead)

            {

                cs.Write(bPlain, 0, (int)bPlain.Length);

                //descsp.BlockSize=64

                lRead = mOut.Length + Convert.ToUInt32(((bPlain.Length / descsp.BlockSize) * descsp.BlockSize));

            };


            ASCIIEncoding aEnc = new ASCIIEncoding();

            strResult = aEnc.GetString(mOut.GetBuffer(), 0, (int)mOut.Length);


            //6. Trim the string to return only the meaningful data

            // Remember that in the encrypt function, the first 5 character holds the length of the actual data

            // This is the simplest way to remember to original length of the data, without resorting to complicated computations.

            String strLen = strResult.Substring(0, 5);

            int nLen = Convert.ToInt32(strLen);

            strResult = strResult.Substring(5, nLen);

            nReturn = (int)mOut.Length;


            return strResult;

        }

        catch (Exception)

        {

            strResult = "Error. Decryption Failed. Possibly due to incorrect Key or corrputed data";

            return strResult;

        }

    }


    /// <summary>

    /// Private function to generate the keys into member variables.

    /// </summary>

    static private bool InitKey(String strThekey)

    {

        try

        {

            // Convert Key to byte array

            byte[] bp = new byte[strThekey.Length];

            ASCIIEncoding aEnc = new ASCIIEncoding();

            aEnc.GetBytes(strThekey, 0, strThekey.Length, bp, 0);


            //Hash the key using SHA1

            SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();

            byte[] bpHash = sha.ComputeHash(bp);


            int i;

            // use the low 64-bits for the key value

            for (i = 0; i < 8; i++)

                m_Key[i] = bpHash[i];


            for (i = 8; i < 16; i++)

                m_IV[i - 8] = bpHash[i];


            return true;

        }

        catch (Exception)

        {

            //Error Performing Operations

            return false;

        }

    }



 


    


}



namespace LuminousCryptoService

{

    /// <summary>

    /// SymmCrypto is a wrapper of System.Security.Cryptography.SymmetricAlgorithm classes

    /// and simplifies the interface. It supports customized SymmetricAlgorithm as well.

    /// </summary>

    public class SymmCrypto

    {

        /// <remarks>

        /// Supported .Net intrinsic SymmetricAlgorithm classes.

        /// </remarks>

        public enum SymmProvEnum : int

        {

            DES, RC2, Rijndael

        }


        private SymmetricAlgorithm mobjCryptoService;


        /// <remarks>

        /// Constructor for using an intrinsic .Net SymmetricAlgorithm class.

        /// </remarks>

        public SymmCrypto(SymmProvEnum NetSelected)

        {

            switch (NetSelected)

            {

                case SymmProvEnum.DES:

                    mobjCryptoService = new DESCryptoServiceProvider();

                    break;

                case SymmProvEnum.RC2:

                    mobjCryptoService = new RC2CryptoServiceProvider();

                    break;

                case SymmProvEnum.Rijndael:

                    mobjCryptoService = new RijndaelManaged();

                    break;

            }

        }


        /// <remarks>

        /// Constructor for using a customized SymmetricAlgorithm class.

        /// </remarks>

        public SymmCrypto(SymmetricAlgorithm ServiceProvider)

        {

            mobjCryptoService = ServiceProvider;

        }


        /// <remarks>

        /// Depending on the legal key size limitations of a specific CryptoService provider

        /// and length of the private key provided, padding the secret key with space character

        /// to meet the legal size of the algorithm.

        /// </remarks>

        private byte[] GetLegalKey(string Key)

        {

            string sTemp;

            if (mobjCryptoService.LegalKeySizes.Length > 0)

            {

                int lessSize = 0, moreSize = mobjCryptoService.LegalKeySizes[0].MinSize;

                // key sizes are in bits

                while (Key.Length * 8 > moreSize)

                {

                    lessSize = moreSize;

                    moreSize += mobjCryptoService.LegalKeySizes[0].SkipSize;

                }

                sTemp = Key.PadRight(moreSize / 8, ' ');

            }

            else

                sTemp = Key;


            // convert the secret key to byte array

            return ASCIIEncoding.ASCII.GetBytes(sTemp);

        }


        public string Encrypting(string Source, string Key)

        {

            byte[] bytIn = System.Text.ASCIIEncoding.ASCII.GetBytes(Source);

            // create a MemoryStream so that the process can be done without I/O files

            System.IO.MemoryStream ms = new System.IO.MemoryStream();


            byte[] bytKey = GetLegalKey(Key);


            // set the private key

            mobjCryptoService.Key = bytKey;

            mobjCryptoService.IV = bytKey;


            // create an Encryptor from the Provider Service instance

            ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();


            // create Crypto Stream that transforms a stream using the encryption

            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);


            // write out encrypted content into MemoryStream

            cs.Write(bytIn, 0, bytIn.Length);

            cs.FlushFinalBlock();


            // get the output and trim the '\0' bytes

            byte[] bytOut = ms.GetBuffer();

            int i = 0;

            for (i = 0; i < bytOut.Length; i++)

                if (bytOut[i] == 0)

                    break;


            // convert into Base64 so that the result can be used in xml

            return System.Convert.ToBase64String(bytOut, 0, i);

        }


        public string Decrypting(string Source, string Key)

        {

            // convert from Base64 to binary

            byte[] bytIn = System.Convert.FromBase64String(Source);

            // create a MemoryStream with the input

            System.IO.MemoryStream ms = new System.IO.MemoryStream(bytIn, 0, bytIn.Length);


            byte[] bytKey = GetLegalKey(Key);


            // set the private key

            mobjCryptoService.Key = bytKey;

            mobjCryptoService.IV = bytKey;


            // create a Decryptor from the Provider Service instance

            ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();


            // create Crypto Stream that transforms a stream using the decryption

            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);


            // read out the result from the Crypto Stream

            System.IO.StreamReader sr = new System.IO.StreamReader(cs);

            return sr.ReadToEnd();

        }

    }

}

No comments:

Post a Comment