File encryption and decryption algorithm design

 

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;


namespace encryption and decryption
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        ///  <Summary> 
        /// exception class
         ///  </ Summary> 
        public  class CryptoHelpException: ApplicationException
        {
            public CryptoHelpException(string msg) : base(msg) { }
        }

        /// <summary>
        /// CryptHelp
        /// </summary>
     
            private const ulong FC_TAG = 0xFC010203040506CF;

            private const int BUFFER_SIZE = 128 * 1024;

            ///  <Summary> 
            /// test Byte two arrays are identical
             ///  </ Summary> 
            ///  <param name = "B1"> Byte array </ param> 
            ///  <param name = "B2" > byte array </ param> 
            ///  <Returns> true-equivalent </ Returns> 
            Private   BOOL CheckByteArrays ( byte [] B1, byte [] B2)
            {
                if (b1.Length == b2.Length)
                {
                    for (int i = 0; i < b1.Length; ++i)
                    {
                        if (b1[i] != b2[i])
                            return false;
                    }
                    return true;
                }
                return false;
            }

            ///  <the Summary> 
            /// create DebugLZQ, http://www.cnblogs.com/DebugLZQ 
            ///  </ the Summary> 
            ///  <param name = "password"> Password </ param> 
            ///  < name = param "Salt"> </ param> 
            ///  <Returns> encryption target </ Returns> 
            Private   the SymmetricAlgorithm CreateRijndael ( String password, byte [] Salt)
            {
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt, "SHA256", 1000);

                SymmetricAlgorithm sma = Rijndael.Create();
                sma.KeySize = 256;
                sma.Key = pdb.GetBytes(32);
                sma.Padding = PaddingMode.PKCS7;
                return sma;
            }

            ///  <Summary> 
            /// encrypted random number generation file
             ///  </ Summary> 
            Private   RandomNumberGenerator RAND = new new the RNGCryptoServiceProvider ();

            ///  <Summary> 
            /// generates a random Byte array specified length
             ///  </ Summary> 
            ///  <param name = "COUNT"> Byte array length </ param> 
            ///  <Returns> random Byte array </ Returns> 
            Private   byte [] generateRandomBytes ( int COUNT)
            {
                byte[] bytes = new byte[count];
                rand.GetBytes(bytes);
                return bytes;
            }

            ///  <Summary> 
            /// encrypted file
             ///  </ Summary> 
            ///  <param name = "inFile"> be encrypted file </ param> 
            ///  <param name = "the outFile"> encrypted input file </ param> 
            ///  <param name = "password"> encryption password </ param> 
            public   void the EncryptFile ( String inFile, String the outFile, String password)
            {
                using (FileStream fin = File.OpenRead(inFile),
                    fout = File.OpenWrite(outFile))
                {
                    Long lSize Number of = fin.Length; // input file length 
                    int size = ( int ) lSize Number of;
                     byte [] bytes = new new  byte [BUFFER_SIZE]; // buffer 
                    int Read = - . 1 ; // input file number of read 
                    int value = 0 ;

                    // Get IV and Salt 
                    byte [] = generateRandomBytes IV ( 16 );
                     byte [] = generateRandomBytes Salt ( 16 );

                    // create an encrypted objects 
                    SymmetricAlgorithm SMA = CreateRijndael (password, Salt);
                    sma.IV = IV;

                    // start writing to the output file section IV and Salt 
                    fout.Write (IV, 0 , IV.Length);
                    fout.Write(salt, 0, salt.Length);

                    // 创建散列加密
                    HashAlgorithm hasher = SHA256.Create();
                    using (CryptoStream cout = new CryptoStream(fout, sma.CreateEncryptor(), CryptoStreamMode.Write),
                        chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
                    {
                        BinaryWriter bw = new BinaryWriter(cout);
                        bw.Write(lSize);

                        bw.Write(FC_TAG);

                        // read byte block encryption stream to buffer 
                        the while ((Read = fin.Read (bytes, 0 , bytes.Length))! = 0 )
                        {
                            cout.Write(bytes, 0, read);
                            chash.Write(bytes, 0, read);
                            value += read;
                        }
                        // Close the encryption stream 
                        chash.Flush ();
                        chash.Close();

                        // reads the hash 
                        byte [] = the hash hasher.Hash;

                        // input file written hash 
                        cout.Write (the hash, 0 , hash.Length);

                        // close the file stream 
                        cout.Flush ();
                        cout.Close();
                    }
                }
            }

            ///  <Summary> 
            /// decrypt files
             ///  </ Summary> 
            ///  <param name = "inFile"> be decrypted file </ param> 
            ///  <param name = "the outFile"> decrypted output file </ param> 
            ///  <param name = "password"> decryption password </ param> 
            public   void DecryptFile ( String inFile, String the outFile, String password)
            {
                // Create a file stream open 
                a using (the FileStream FIN = File.OpenRead (inFile),
                    fout = File.OpenWrite(outFile))
                {
                    int size = (int)fin.Length;
                    byte[] bytes = new byte[BUFFER_SIZE];
                    int read = -1;
                    int value = 0;
                    int outValue = 0;

                    byte[] IV = new byte[16];
                    fin.Read(IV, 0, 16);
                    byte[] salt = new byte[16];
                    fin.Read(salt, 0, 16);

                    SymmetricAlgorithm sma =CreateRijndael(password, salt);
                    sma.IV = IV;

                    value = 32;
                    long lSize = -1;

                    // create a hash object, check the file 
                    HashAlgorithm Hasher = SHA256.Create ();

                    using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read),
                        chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
                    {
                        // read the file length of 
                        the BinaryReader br = new new the BinaryReader (CIN);
                        lSize = br.ReadInt64();
                        ulong tag = br.ReadUInt64();

                        IF (FC_TAG =! Tag)
                             the throw  new new CryptoHelpException ( " The file is corrupted " );

                        long numReads = lSize / BUFFER_SIZE;

                        long slack = (long)lSize % BUFFER_SIZE;

                        for (int i = 0; i < numReads; ++i)
                        {
                            read = cin.Read(bytes, 0, bytes.Length);
                            fout.Write(bytes, 0, read);
                            chash.Write(bytes, 0, read);
                            value += read;
                            outValue += read;
                        }

                        if (slack > 0)
                        {
                            read = cin.Read(bytes, 0, (int)slack);
                            fout.Write(bytes, 0, read);
                            chash.Write(bytes, 0, read);
                            value += read;
                            outValue += read;
                        }

                        chash.Flush ();
                        chash.Close();

                        fout.Flush();
                        fout.Close();

                        byte[] curHash = hasher.Hash;

                        // Get the old hash object and compare 
                        byte [] = oldHash new new  byte [hasher.HashSize / . 8 ];
                        read = cin.Read(oldHash, 0, oldHash.Length);
                        if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash)))
                            throw new CryptoHelpException("文件被破坏");
                    }

                    IF (! = outValue lSize Number of)
                         the throw  new new CryptoHelpException ( " File Size mismatch " );
                }
            }
      

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = " Choose storage path " ;
             IF (dialog.ShowDialog () == DialogResult.OK)
            {
                wjj.Text = dialog.SelectedPath;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (wjj.Text == "")
            {
                MessageBox.Show ( " Please select the folder! " );
            }
            else
            {
                DirectoryInfo dir = new DirectoryInfo(wjj.Text);
                FileInfo[] allFile = dir.GetFiles();
                if (!Directory.Exists(wjj.Text + "/加密"))
                {
                    Directory.CreateDirectory(wjj.Text + "/加密");
                }
                foreach (FileInfo file in allFile)
                {

                    string inFile = wjj.Text + "/" + file.Name;
                   
                    string outFile = wjj.Text + "/加密/" + file.Name; ;
                    string password = txtPassword.Text;
                    EncryptFile (inFile, the outFile, password); // encrypt files
                                                            // delete files before encryption 
                    File.Delete (inFile);

                }
                //   txtFileName.Text = string.Empty; 
                MessageBox.Show ( " Encryption success " );
            }


         
         
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (wjj.Text == "") {
                MessageBox.Show ( " Please select the folder! " );
            }
            else
            {
                DirectoryInfo dir = new DirectoryInfo(wjj.Text);
                FileInfo[] allFile = dir.GetFiles();
                if (!Directory.Exists(wjj.Text + "/解密"))
                {
                    Directory.CreateDirectory(wjj.Text + "/解密");
                }
                foreach (FileInfo file in allFile)
                {
                    string inFile = wjj.Text + "/" + file.Name;
                    string outFile = wjj.Text + "/解密/" + file.Name; ;
                    string password = txtPassword.Text;
                    DecryptFile (inFile, the outFile, password); // decrypt the file
                                                            // delete the file before decrypting 
                    File.Delete (inFile);
                }
                //   txtFileName.Text = string.Empty; 
                MessageBox.Show ( " decryption is successful " );
            }
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/Jeely/p/11721280.html