File encryption and decryption

 

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace DESFile
{
    ///  <Summary>  
    /// exception class 
     ///  </ Summary>  
    public  class CryptoHelpException: ApplicationException
    {
        public CryptoHelpException(string msg) : base(msg) { }
    }
    /// <summary> 
    /// CryptHelp 
    /// </summary> 
    public class DESFileClass
    {
        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  static  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  static 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  static RandomNumberGenerator RAND = new new the RNGCryptoServiceProvider ();
         ///  <Summary>  
        /// generates a random array of given length Byte 
         ///  </ Summary>  
        ///  <param name = "COUNT"> byte array length </ param>  
        ///  <Returns> random byte array </ Returns>  
        Private  static  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  static  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 encryption target 
                SymmetricAlgorithm sma = DESFileClass.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 write hash 
                    cout.Write (the hash, 0 , hash.Length);
                     // close 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  static  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 = DESFileClass.CreateRijndael(password, salt);
                sma.IV = IV;
                value = 32 ;
                 Long lSize Number of = - . 1 ;
                 // Create an object hash, checksum file 
                the HashAlgorithm Hasher = SHA256.Create ();
                 the using (CIN = the CryptoStream new new the 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)
                        throw new CryptoHelpException("文件被破坏");
                    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 comparing 
                    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 " );
            }
        }
    } 
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace jiami
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string inFile = textBox1.Text;
            string outFile = inFile + ".ac";
            string password = textBox2.Text;
            DESFile.DESFileClass.EncryptFile (inFile, the outFile, password); // encrypt files 
             // delete files before encryption 
            File.Delete (inFile);
            textBox1.Text = string.Empty;
            MessageBox.Show ( " Encryption success " );
         } 
            private void button3_Click(object sender, EventArgs e)
            {
                OpenFileDialog f = new OpenFileDialog();
                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    textBox1.Text = f.FileName;
                } 
            }

            private void button2_Click(object sender, EventArgs e)
            {
                string inFile = textBox1.Text;
                string outFile = inFile.Substring(0, inFile.Length - 4);
                string password = textBox2.Text;
                DESFile.DESFileClass.DecryptFile (inFile, the outFile, password); // decrypt the file 
                 // delete the file before decrypting 
                File.Delete (inFile);
                textBox1.Text = string.Empty;
                MessageBox.Show ( " decryption is successful " );
            }
    }
}

 

Guess you like

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