SoFunction
Updated on 2025-03-07

C# encryption and decryption instance program


using System;
using ;
using ;
using ;

namespace SEDO
{
    /// <summary>
/// Summary description of SEDO.
/// SEDO implements a component that encapsulates 4 symmetric encryption methods (Des, Rc2, Rijndael, TripleDes)
    ///
/// Notes:
/// 1: TripleDes and Rijndael encrypted/decrypted objects using 16 or 24-bit key
/// 2: Rijndael can only use 16-bit initialization vector IV
/// 3: Des and Rc2 both use 8-bit Byte Key and IV
/// 4: What method should be used to encode/decrypt the data stream that needs to be encrypted/decrypted to be determined by the user who calls the component
/// 5: The key and initialization vector IV are defined by the user themselves
/// Programmer: Luo Xucheng 2010-10-30 lxc880615@
    /// </summary>

//Define the enumeration of encryption type
    public enum EncryptionAlgorithm { Des = 1, Rc2, Rijndael, TripleDes };

//Define 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 initialization vector IV is empty,
//The key generated automatically by the encrypted object will be used or the vector IV will be initialized.
            switch (algorithmID)
            {
                case :
                    {
                        DES des = new DESCryptoServiceProvider();
                        = ;

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

//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;
        }

//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 initialization vector IV is empty,
//The key generated automatically by the encrypted object will be used or the vector IV will be initialized.
            switch (algorithmID)
            {
                case :
                    {
                        DES des = new DESCryptoServiceProvider();
                        = ;
                        = bytesKey;
                        = initVec;
                        return ();
                    }
                case :
                    {
                        TripleDES des3 = new TripleDESCryptoServiceProvider();
                        = ;
                        return (bytesKey, initVec);
                    }
                case EncryptionAlgorithm.Rc2:
                    {
                        RC2 rc2 = new RC2CryptoServiceProvider();
                        = ;
                        return (bytesKey, initVec);
                    }
                case :
                    {
                        Rijndael rijndael = new RijndaelManaged();
                        = ;
                        return (bytesKey, initVec);
                    }
                default:
                    {
                        throw new CryptographicException("Algorithm ID '" +
                        algorithmID +
                        "' not supported.");
                    }
            }
        } //end GetCryptoServiceProvider

    }

//Define the cryptor 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 save encrypted data byte streams.
            MemoryStream memStreamEncryptedData = new MemoryStream();

            = bytesIV;
            = bytesKey;

            ICryptoTransform transform =
                (bytesKey);
            CryptoStream encStream =
                new CryptoStream(memStreamEncryptedData,
                    transform, );

            try
            {
//Write encrypted data into streaming object
                (bytesData, 0, );
            }
            catch (Exception ex)
            {
throw new Exception("An error occurred while data encryption!"+
"Error prompt: \n" + );
            }

//Set the encrypted Key and initial vector IV properties
            encKey = ;
            initVec = ;

            ();
            ();

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

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

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

    }

 
//Define the decryptor 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 save decrypted data byte streams.
            MemoryStream memStreamDecryptedData =
                new MemoryStream();

            //Pass in the initialization vector.
            = bytesIV;
            = bytesKey;

            ICryptoTransform transform =
                (bytesKey);
            CryptoStream decStream =
                new CryptoStream(memStreamDecryptedData,
                    transform, );

            try
            {
                (bytesData, 0, );
            }
            catch (Exception ex)
            {
throw new Exception("An error occurred while decrypting the data!"+
"Error prompt: \n" + );
            }
            ();
            ();
// Return decrypted data.
            return ();
        }

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

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

    }

//Class description: File encryption/decryption class
    public class SecurityFile
    {
private DecryptTransformer Dec_Transformer; //Decrypt 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);
        }

//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: Encrypted file
        public void EncryptFile(string inFileName,
            string outFileName, byte[] bytesKey, byte[] bytesIV)
        {
            try
            {
                FileStream fin =
                    new FileStream(inFileName, ,
                        );
                FileStream fout = new FileStream(outFileName,
                    , );
                (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 = ;
                //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, );

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

                ();
                ();
                ();
            }
            catch (Exception ex)
            {
throw new Exception("An error occurred while encrypting the file!"+
"Error prompt: \n" + );
            }
        }

//Function description: Decrypt the file
        public void DecryptFile(string inFileName,
            string outFileName, byte[] bytesKey, byte[] bytesIV)
        {
            try
            {
                FileStream fin =
                    new FileStream(inFileName, ,
                        );
                FileStream fout =
                    new FileStream(outFileName,
                        , );
                (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 = ;
                //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, );

                //Read from the input file, then encrypt and
                //write to the output file.
                while (rdlen < totlen)
                {
                    len = (bin, 0, 100);
                    (bin, 0, len);
                    rdlen = rdlen + len;
                }
                ();
                ();
                ();
            }
            catch (Exception ex)
            {
throw new Exception("appears when file encryption"+
"Error! Error prompt: \n" + );
            }
        }
    }
}