Ejemplo n.º 1
0
        ///<summary>
        ///	<para>
        ///		This method decrypts the given input file in either of the 2 algorithms 'DES' or 'RC2'.
        ///		Then it writes out the decrypted file
        ///	</para>
        /// <para>
        ///		This method first reads the input file to check to see if its encrypted by which
        ///		algorithm. then it automatically decrypts the file.
        ///	</para>
        /// <para>
        ///		It reads the first 8 bytes of the encrypted file to find the custom tag that we place
        ///     while encrypting.
        ///		If it finds "[saudes]" it uses the 'DES' algorithm to decrypt
        ///		If it finds "[saurc2]" it uses the 'RC2' algorithm to decrypt
        /// </para>
        ///</summary>

        private void DecryptData()
        {
            //try-catch block
            try{
                statusBar1.Text = "Decrypting....";
                //open file streams to the input and outfiles
                FileStream fin  = new FileStream(opent.Text, FileMode.Open, FileAccess.Read);
                FileStream fout = new FileStream(savet.Text, FileMode.OpenOrCreate, FileAccess.Write);
                fout.SetLength(0);

                //a variable to check the validity of the input file
                bool filecheck = false;

                //make a byte array of the size 64 bits
                //this is called the 'Buffer Size' of the algorithm
                //i.e. while encrypting blocks of the size 64bits are processed at a single time
                //later other blocks are of the same size.
                //we use 64bits because both 'DES' and 'RC2' both algorithms have 64 bit 'Buffer Size'

                byte[] bin    = new byte[4096];
                long   totlen = fin.Length;
                long   rdlen  = 8;
                int    len;
                // declare a object of type 'SymmetricAlgorithm'
                SymmetricAlgorithm des;
                //set a tempory variable to length '8' (we use '8' since the size of the tag put in the file is 8 chars long)
                byte[] tag = new byte[8];
                //read the first 8 bytes from the input file to check which algrothim is used to encrypt the file
                fin.Read(tag, 0, tag.Length);

                if ((tag[0] == (byte)'[') && (tag[1] == (byte)'S') && (tag[2] == (byte)'a') && (tag[3] == (byte)'u') && (tag[4] == (byte)'d') && (tag[5] == (byte)'e') && (tag[6] == (byte)'s') && (tag[7] == (byte)']'))
                {
                    //If this is true then the 'DES' algorithm has been used to encrypt the file
                    //so set the variable 'des' to new 'DES_CSP'
                    des = new DES_CSP();
                    //set the variable to true since the file is encrypted
                    filecheck = true;
                    //generate the Key and Vector from the given password
                    //we send 'true' here since the algorithm used is 'DES'
                    GenerateKee(true);
                }
                else if ((tag[0] == (byte)'[') && (tag[1] == (byte)'S') && (tag[2] == (byte)'a') && (tag[3] == (byte)'u') && (tag[4] == (byte)'r') && (tag[5] == (byte)'c') && (tag[6] == (byte)'2') && (tag[7] == (byte)']'))
                {
                    //if this is true then the 'RC2' algorithm has been used to encrypt the file
                    //so we set the variable 'des' to new 'RC2_CSP'
                    des = new RC2_CSP();
                    //set the keysize of the algorithm
                    des.KeySize = 40;
                    //set thevariable to true since it is encrypted
                    filecheck = true;
                    //generate the Key and Vector from the password given by the user
                    //we pass false here since we are using 'RC2' algorithm
                    GenerateKee(false);
                }
                else
                {
                    MessageBox.Show("File Error !! File does not seem to be encrypted by SymEncryptor !!");
                    //set the des to null so no encryption occurs
                    des             = null;
                    statusBar1.Text = "Error ";
                }
                //if the file is encrypted then decrypt it
                if (filecheck)
                {
                    //create a object of the inner class 'StoreCryptoStream'
                    //we pass it the FileStream
                    StoreCryptoStream scs = new StoreCryptoStream(fout);
                    //make a object of this stream passing the Key and Vector
                    //we use this strem since it helps us decrypt data from a
                    //encrypted file
                    SymmetricStreamDecryptor ssd = des.CreateDecryptor(symKey, symIV);
                    //set up the streams
                    ssd.SetSink(scs);
                    scs.SetSource(ssd);
                    //read the full encrypted file and decrypt
                    while (rdlen < totlen)
                    {
                        //set the length of the number of bytes read
                        len = fin.Read(bin, 0, 4096);
                        //write the decrypted data
                        ssd.Write(bin, 0, len);
                        //increase the total read bytes variable
                        rdlen = rdlen + len;
                    }
                    //free up the resources
                    ssd.CloseStream();
                }
                fin.Close();
                fout.Close();
                statusBar1.Text = "Decryption Compelete";
            }
            catch (Exception e)
            {
                MessageBox.Show("An exception occured while decrypting :" + e.ToString());
                statusBar1.Text = "Error";
            }
        }
Ejemplo n.º 2
0
        ///<summary>
        ///	<para>
        ///		This method encrypts the given input file in either of the 2 algorithms 'DES' or 'RC2'.
        ///		Then it writes out the encrypted file
        ///	</para>
        /// <para>
        ///		This method first reads the input file to check to see if its already encrypted by this
        ///		same program. If its already encrypted it gives a error.
        ///	</para>
        /// <para>
        ///		According to the algorithm specified it then encrypts the file.
        ///		Also in the first 8 bytes of the new Encrypted it writes out "[saudes]" or "[saurc2]"
        ///		This is done so the while decrypting the program can know which algorithm was used to
        ///		encrypt the file. Also it used to check if the file has already encrypted
        /// </para>
        ///</summary>
        private void EncryptData()
        {
            //try-catch block
            try{
                bool algo;           //a boolean variable to check which algorithm to use in encrypting
                                     //open the 'FileStream' on the file to be encrypted
                FileStream fin = new FileStream(opent.Text, FileMode.Open, FileAccess.Read);
                //Make a file to save the encrypted data to and open a 'FileStream' on it
                FileStream fout = new FileStream(savet.Text, FileMode.OpenOrCreate, FileAccess.Write);
                //set the position of the 'cursor' to the start of the file
                fout.SetLength(0);
                //make a byte array of the size 64 bits
                //this is called the 'Buffer Size' of the algorithm
                //i.e. while encrypting blocks of the size 64bits are processed at a single time
                //later other blocks are of the same size.
                //we use 64bits because both 'DES' and 'RC2' both algorithms have 64 bit 'Buffer Size'
                byte[] bin = new byte[4096];
                //set the total length of the file to me encrypted to a variable
                long totlen = fin.Length;
                long rdlen  = 0;
                int  len;
                //the code below is used to check if the file has already been encrypted by this program
                //make a byte array of length '4'
                byte[] tag = new byte[4];
                //read the first 4 bytes from the file to be encrypted
                fin.Read(tag, 0, tag.Length);
                //if it contains the chars "[sau" then it has been already encrypted by this program
                if ((tag[0] == (byte)'[') && (tag[1] == (byte)'S') && (tag[2] == (byte)'a') && (tag[3] == (byte)'u'))
                {
                    //genrate a error to let the user know of the error
                    MessageBox.Show("This file is already Encrypted or in Invalid format!");
                    statusBar1.Text = "Error - Invalid File Format !!";
                }

                else
                {
                    //if the file if ok the proceed with encryption
                    statusBar1.Text = "Encrypting...";
                    //set the file read cursor back to the 'Begning' of the opened file
                    fin.Seek(0, SeekOrigin.Begin);
                }
                //make a object of the class 'SymmetricAlgorithm'
                SymmetricAlgorithm des;
                if (radioButton1.Checked)
                {
                    //if the algorithm to be used is 'DES' then initilize the 'SymmetricAlgorithm' to 'DES_CSP'
                    des = new DES_CSP();
                    //set the variable to true because we are using 'DES' algorithm.
                    algo = true;
                }
                else
                {
                    //if the algorithm to be used is 'RC2' then initilize the variable 'des' to 'RC2_CSP'
                    des = new RC2_CSP();
                    //set the key size of the algorithm to 40 bits since we are using a 40 bit key
                    des.KeySize = 40;

                    //uncomment the below code to kind out the bits of keys supported by RC2 algorithm

                    /*KeySizes[] ks = des.LegalKeySizes ;
                     * Console.WriteLine("Key Sizes Supported :") ;
                     * Console.WriteLIne("Minimum Size:" +ks[0].MinSize) ;
                     * Console.WriteLine("Skip size of key: "+ks[0].SkipSize) ;
                     * Console.WriteLine("Maximum Size: "+ks[0].MaxSize) ;
                     */

                    //set the bool variable to false since we are using the RC2 algorithm
                    algo = false;
                }

                //Make a object of the inner class 'StoreCryptoStream' we pass the bool variable
                //containing the algotithm information and the FileStream
                StoreCryptoStream scs = new StoreCryptoStream(algo, fout);

                //make an object of the 'SymmetricStreamEncryptor' class and pass it the 'Key and the 'Vector'
                //this starem helps to encrypt data according to the algorithm used
                SymmetricStreamEncryptor sse = des.CreateEncryptor(symKey, symIV);

                // a little extra feature here to show how to compose crypto
                // components that support ICryptoStream
                SHA1_CSP sha = new SHA1_CSP();

                // wire up the encryptor - hash - StoreCryptoStream
                sse.SetSink(sha);
                sha.SetSource(sse);
                sha.SetSink(scs);
                scs.SetSource(sha);

                //read from the file to encrypt
                while (rdlen < totlen)
                {
                    //set the number of bytes read
                    len = fin.Read(bin, 0, 4096);
                    //write the encrypted data
                    sse.Write(bin, 0, len);
                    //increase the size of bytes read
                    rdlen = rdlen + len;
                }
                //free up the resources
                sse.CloseStream();

                fin.Close();
                fout.Close();
                statusBar1.Text = "Encryption Compelete !";
            }
            catch (Exception e)
            {
                MessageBox.Show("An exception occured while encrypting :" + e.ToString());
                statusBar1.Text = "Error";
            }
        }