C encryption decryption class instance procedures

  • 2020-05-26 09:56:28
  • OfStack

What I wrote in the previous two years, I am now sorting out 1 and sending it out! Before, the company needed to do WebService and encrypt SoapHeader of WebService, so it wrote something like this! Using this class requires key management! In order to ensure the security of the data, it is necessary to encrypt the data. However, one of the disadvantages of encryption is that it affects the operation efficiency of the program. Therefore, at that time, my idea was to encrypt only the user's login information (user name and password)! The data is transmitted in clear text. If the user information fails to pass the verification, the data is not transmitted.
In fact, in network communication, the way to use secret keys is not invulnerable. If a hacker can capture user authentication information encrypted with a key, and then make a simulated request to the server that provides WebService, he can still get the requested data! So, I used IP or domain name binding again! After all, WebService is not directly available to end users! So, add all this to the mix, and even those with bad intentions who want to gain access to WebService's services illegally will have to work harder.
Another point of security advice is to change the key regularly. In this case, I used symmetric encryption. Regular key changes can improve security by a lot!

We want to have a better method, or Suggestions, you can leave a message to discuss 1! Improve together!

The code is as follows:


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

namespace SEDO
{
    /// <summary>
    /// SEDO  A summary of. 
    /// SEDO  What is achieved is used 1 An encapsulated 4 A symmetric encryption method is proposed (Des,Rc2,Rijndael,TripleDes) The components of the 
    ///
    ///  Matters needing attention: 
    /// 1:TripleDes and Rijndael encryption / Use of decryption object 16 or 24 position byte the Key
    /// 2:Rijndael Can only use 16 Bit initialization vector IV
    /// 3:Des and Rc2 use 8 position Byte the Key and IV
    /// 4: Need to be encrypted / How the decrypted data stream is encoded / Decoding is up to the user who calls the component 
    /// 5: The key and the initialization vector IV It is defined by the user 
    ///  Programmer:   Luo Xucheng 2010-10-30 lxc880615@163.com
    /// </summary>

    // Defines an enumeration of encryption types 
    public enum EncryptionAlgorithm { Des = 1, Rc2, Rijndael, TripleDes };

    // Define the encryption class 
    internal class EncryptTransformer
    {
        private EncryptionAlgorithm algorithmID;
        private byte[] initVec;
        private byte[] encKey;

        internal EncryptTransformer(EncryptionAlgorithm algId)
        {
            //Save the algorithm being used.
            algorithmID = algId;
        }

        internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
        {
            // When the data key Key Or initialize the vector IV When it's empty, 
            // The key automatically generated by the encryption object will be used Key Or initialize the vector IV
            switch (algorithmID)
            {
                case EncryptionAlgorithm.Des:
                    {
                        DES des = new DESCryptoServiceProvider();
                        des.Mode = CipherMode.CBC;

                        // See if a key was provided
                        if (null == bytesKey)
                        {
                            encKey = des.Key;
                        }
                        else
                        {
                            des.Key = bytesKey;
                            encKey = des.Key;
                        }
                        // See if the client provided an initialization vector
                        if (null == initVec)
                        { // Have the algorithm create one
                            initVec = des.IV;
                        }
                        else
                        { //No, give it to the algorithm
                            des.IV = initVec;
                        }
                        return des.CreateEncryptor();
                    }
                case EncryptionAlgorithm.TripleDes:
                    {
                        TripleDES des3 = new TripleDESCryptoServiceProvider();
                        des3.Mode = CipherMode.CBC;
                        // See if a key was provided
                        if (null == bytesKey)
                        {
                            encKey = des3.Key;
                        }
                        else
                        {
                            des3.Key = bytesKey;
                            encKey = des3.Key;
                        }
                        // See if the client provided an IV
                        if (null == initVec)
                        { //Yes, have the alg create one
                            initVec = des3.IV;
                        }
                        else
                        { //No, give it to the alg.
                            des3.IV = initVec;
                        }
                        return des3.CreateEncryptor();
                    }
                case EncryptionAlgorithm.Rc2:
                    {
                        RC2 rc2 = new RC2CryptoServiceProvider();
                        rc2.Mode = CipherMode.CBC;
                        // Test to see if a key was provided
                        if (null == bytesKey)
                        {
                            encKey = rc2.Key;
                        }
                        else
                        {
                            rc2.Key = bytesKey;
                            encKey = rc2.Key;
                        }
                        // See if the client provided an IV
                        if (null == initVec)
                        { //Yes, have the alg create one
                            initVec = rc2.IV;
                        }
                        else
                        { //No, give it to the alg.
                            rc2.IV = initVec;
                        }
                        return rc2.CreateEncryptor();
                    }
                case EncryptionAlgorithm.Rijndael:
                    {
                        Rijndael rijndael = new RijndaelManaged();
                        rijndael.Mode = CipherMode.CBC;
                        // Test to see if a key was provided
                        if (null == bytesKey)
                        {
                            encKey = rijndael.Key;
                        }
                        else
                        {
                            rijndael.Key = bytesKey;
                            encKey = rijndael.Key;
                        }
                        // See if the client provided an IV
                        if (null == initVec)
                        { //Yes, have the alg create one
                            initVec = rijndael.IV;
                        }
                        else
                        { //No, give it to the alg.
                            rijndael.IV = initVec;
                        }
                        return rijndael.CreateEncryptor();
                    }
                default:
                    {
                        throw new CryptographicException("Algorithm ID '" +
                        algorithmID +
                        "' not supported.");
                    }
            }
        }

        // The encrypted offset vector 
        internal byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }
        // Encrypted key 
        internal byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

    }

    // Define the decryption class 
    internal class DecryptTransformer
    {
        private EncryptionAlgorithm algorithmID;
        private byte[] initVec;
        private byte[] encKey;

        internal DecryptTransformer(EncryptionAlgorithm deCryptId)
        {
            algorithmID = deCryptId;
        }

        // The encrypted offset vector 
        internal byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }

        // Encrypted key 
        internal byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

        internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
        {
            // When the data key Key Or initialize the vector IV When it's empty, 
            // The key automatically generated by the encryption object will be used Key Or initialize the vector IV
            switch (algorithmID)
            {
                case EncryptionAlgorithm.Des:
                    {
                        DES des = new DESCryptoServiceProvider();
                        des.Mode = CipherMode.CBC;
                        des.Key = bytesKey;
                        des.IV = initVec;
                        return des.CreateDecryptor();
                    }
                case EncryptionAlgorithm.TripleDes:
                    {
                        TripleDES des3 = new TripleDESCryptoServiceProvider();
                        des3.Mode = CipherMode.CBC;
                        return des3.CreateDecryptor(bytesKey, initVec);
                    }
                case EncryptionAlgorithm.Rc2:
                    {
                        RC2 rc2 = new RC2CryptoServiceProvider();
                        rc2.Mode = CipherMode.CBC;
                        return rc2.CreateDecryptor(bytesKey, initVec);
                    }
                case EncryptionAlgorithm.Rijndael:
                    {
                        Rijndael rijndael = new RijndaelManaged();
                        rijndael.Mode = CipherMode.CBC;
                        return rijndael.CreateDecryptor(bytesKey, initVec);
                    }
                default:
                    {
                        throw new CryptographicException("Algorithm ID '" +
                        algorithmID +
                        "' not supported.");
                    }
            }
        } //end GetCryptoServiceProvider

    }

    // Define the jammer class 
    public class Encryptor
    {
        private EncryptTransformer transformer;
        private byte[] initVec;
        private byte[] encKey;

        public Encryptor(EncryptionAlgorithm algId)
        {
            transformer = new EncryptTransformer(algId);
        }

        public byte[] Encrypt(byte[] bytesData, byte[] bytesKey, byte[] bytesIV)
        {
            // Set the stream object to hold the encrypted data byte stream .
            MemoryStream memStreamEncryptedData = new MemoryStream();

            transformer.IV = bytesIV;
            transformer.Key = bytesKey;

            ICryptoTransform transform =
                transformer.GetCryptoServiceProvider(bytesKey);
            CryptoStream encStream =
                new CryptoStream(memStreamEncryptedData,
                    transform, CryptoStreamMode.Write);

            try
            {
                // Writes the encrypted data into the stream object 
                encStream.Write(bytesData, 0, bytesData.Length);
            }
            catch (Exception ex)
            {
                throw new Exception(" Error in data encryption! "+
                    " Error:  \n" + ex.Message);
            }

            // Set encrypted Key And the initial vector IV attribute 
            encKey = transformer.Key;
            initVec = transformer.IV;

            encStream.FlushFinalBlock();
            encStream.Close();

            //Send the data back.
            return memStreamEncryptedData.ToArray();
        }

        public byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }

        public byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

    }

 
    // Define the decoder class 
    public class Decryptor
    {
        private DecryptTransformer transformer;
        private byte[] initVec;
        private byte[] encKey;

        public Decryptor(EncryptionAlgorithm algId)
        {
            transformer = new DecryptTransformer(algId);
        }

        public byte[] Decrypt(byte[] bytesData,
            byte[] bytesKey, byte[] bytesIV)
        {
            // Set the stream object to hold the decrypted data stream .
            MemoryStream memStreamDecryptedData =
                new MemoryStream();

            //Pass in the initialization vector.
            transformer.IV = bytesIV;
            transformer.Key = bytesKey;

            ICryptoTransform transform =
                transformer.GetCryptoServiceProvider(bytesKey);
            CryptoStream decStream =
                new CryptoStream(memStreamDecryptedData,
                    transform, CryptoStreamMode.Write);

            try
            {
                decStream.Write(bytesData, 0, bytesData.Length);
            }
            catch (Exception ex)
            {
                throw new Exception(" Error in data decryption! "+
                    " Error:  \n" + ex.Message);
            }
            decStream.FlushFinalBlock();
            decStream.Close();
            //  Return decrypted data .
            return memStreamDecryptedData.ToArray();
        }

        public byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }

        public byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

    }

    // Class description: file encryption / Decryption classes 
    public class SecurityFile
    {
        private DecryptTransformer Dec_Transformer; // Decryption converter 
        private EncryptTransformer Enc_Transformer; // Encryption converter 
        private byte[] initVec;
        private byte[] encKey;

        public SecurityFile(EncryptionAlgorithm algId)
        {
            Dec_Transformer = new DecryptTransformer(algId);
            Enc_Transformer = new EncryptTransformer(algId);
        }

        // The encrypted offset vector 
        internal byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }
        // Encrypted key 
        internal byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

        // Function description: encrypt files 
        public void EncryptFile(string inFileName,
            string outFileName, byte[] bytesKey, byte[] bytesIV)
        {
            try
            {
                FileStream fin =
                    new FileStream(inFileName, FileMode.Open,
                        FileAccess.Read);
                FileStream fout = new FileStream(outFileName,
                    FileMode.OpenOrCreate, FileAccess.Write);
                fout.SetLength(0);

                //Create variables to help with read and write.
                //This is intermediate storage for the encryption.
                byte[] bin = new byte[100];
                //This is the total number of bytes written.
                long rdlen = 0;
                //This is the total length of the input file.
                long totlen = fin.Length;
                //This is the number of bytes to be written at a time.
                int len; 

                Enc_Transformer.IV = bytesIV;
                Enc_Transformer.Key = bytesKey;

                ICryptoTransform transform =
                    Enc_Transformer.GetCryptoServiceProvider(bytesKey);
                CryptoStream encStream =
                    new CryptoStream(fout, transform, CryptoStreamMode.Write);

                //Read from the input file, then encrypt and write to the output file.
                while (rdlen < totlen)
                {
                    len = fin.Read(bin, 0, 100);
                    encStream.Write(bin, 0, len);
                    rdlen = rdlen + len;
                }

                encStream.Close();
                fout.Close();
                fin.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(" An error occurred while encrypting the file! "+
                    " Error:  \n" + ex.Message);
            }
        }

        // Function description: decrypt files 
        public void DecryptFile(string inFileName,
            string outFileName, byte[] bytesKey, byte[] bytesIV)
        {
            try
            {
                FileStream fin =
                    new FileStream(inFileName, FileMode.Open,
                        FileAccess.Read);
                FileStream fout =
                    new FileStream(outFileName,
                        FileMode.OpenOrCreate, FileAccess.Write);
                fout.SetLength(0);

                //Create variables to help with read and write.
                //This is intermediate storage for the encryption.
                byte[] bin = new byte[100];
                //This is the total number of bytes written.
                long rdlen = 0;
                //This is the total length of the input file.
                long totlen = fin.Length;
                //This is the number of bytes to be written at a time.
                int len; 

                Dec_Transformer.IV = bytesIV;
                Dec_Transformer.Key = bytesKey;

                ICryptoTransform transform =
                    Dec_Transformer.GetCryptoServiceProvider(bytesKey);
                CryptoStream encStream =
                    new CryptoStream(fout, transform, CryptoStreamMode.Write);

                //Read from the input file, then encrypt and
                //write to the output file.
                while (rdlen < totlen)
                {
                    len = fin.Read(bin, 0, 100);
                    encStream.Write(bin, 0, len);
                    rdlen = rdlen + len;
                }
                encStream.Close();
                fout.Close();
                fin.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(" Occurs when the file is encrypted "+
                    " Error! Error:  \n" + ex.Message);
            }
        }
    }
}


Related articles: