SoFunction
Updated on 2025-03-01

Summary of C# file encryption methods

This article summarizes the C# file encryption method. Share it for your reference. The specific implementation method is as follows:

1. AES encryption class

Copy the codeThe code is as follows:

using System;
using ;
using ;
using ;

namespace Utils
{
    /// <summary>
/// AES encryption and decryption
    /// </summary>
    public class AES
    {
#region Encryption
#region Encrypted string
        /// <summary>
/// AES encryption (advanced encryption standard, which is the next generation of encryption algorithm standard, fast speed and high security level. One implementation of the current AES standard is the Rijndael algorithm)
        /// </summary>
/// <param name="EncryptString">Crypto text to be encrypted</param>
/// <param name="EncryptKey">Encrypt Key</param>
        public static string AESEncrypt(string EncryptString, string EncryptKey)
        {
            return Convert.ToBase64String(AESEncrypt((EncryptString), EncryptKey));
        }
        #endregion

#region Encrypted byte array
        /// <summary>
/// AES encryption (advanced encryption standard, which is the next generation of encryption algorithm standard, fast speed and high security level. One implementation of the current AES standard is the Rijndael algorithm)
        /// </summary>
/// <param name="EncryptString">Crypto text to be encrypted</param>
/// <param name="EncryptKey">Encrypt Key</param>
        public static byte[] AESEncrypt(byte[] EncryptByte, string EncryptKey)
        {
if ( == 0) { throw (new Exception("The plain text must not be empty")); }
if ((EncryptKey)) { throw (new Exception("The key must not be empty")); }
            byte[] m_strEncrypt;
            byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ==");
            byte[] m_salt = Convert.FromBase64String("gsf4jvkyhye5/d7k8OrLgM==");
            Rijndael m_AESProvider = ();
            try
            {
                MemoryStream m_stream = new MemoryStream();
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(EncryptKey, m_salt);
                ICryptoTransform transform = m_AESProvider.CreateEncryptor((32), m_btIV);
                CryptoStream m_csstream = new CryptoStream(m_stream, transform, );
                m_csstream.Write(EncryptByte, 0, );
                m_csstream.FlushFinalBlock();
                m_strEncrypt = m_stream.ToArray();
                m_stream.Close(); m_stream.Dispose();
                m_csstream.Close(); m_csstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_AESProvider.Clear(); }
            return m_strEncrypt;
        }
        #endregion
        #endregion

#region Decryption
#region Decrypt string
        /// <summary>
/// AES decryption (Advanced encryption standard, the next generation of encryption algorithm standard, fast speed and high security level. One implementation of the current AES standard is the Rijndael algorithm)
        /// </summary>
/// <param name="DecryptString">cipher text to be decrypted</param>
/// <param name="DecryptKey">Decrypt key</param>
        public static string AESDecrypt(string DecryptString, string DecryptKey)
        {
            return Convert.ToBase64String(AESDecrypt((DecryptString), DecryptKey));
        }
        #endregion

#region Decrypts byte array
        /// <summary>
/// AES decryption (Advanced encryption standard, the next generation of encryption algorithm standard, fast speed and high security level. One implementation of the current AES standard is the Rijndael algorithm)
        /// </summary>
/// <param name="DecryptString">cipher text to be decrypted</param>
/// <param name="DecryptKey">Decrypt key</param>
        public static byte[] AESDecrypt(byte[] DecryptByte, string DecryptKey)
        {
if ( == 0) { throw (new Exception("The ciphertext must not be empty")); }
if ((DecryptKey)) { throw (new Exception("The key must not be empty")); }
            byte[] m_strDecrypt;
            byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ==");
            byte[] m_salt = Convert.FromBase64String("gsf4jvkyhye5/d7k8OrLgM==");
            Rijndael m_AESProvider = ();
            try
            {
                MemoryStream m_stream = new MemoryStream();
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(DecryptKey, m_salt);
                ICryptoTransform transform = m_AESProvider.CreateDecryptor((32), m_btIV);
                CryptoStream m_csstream = new CryptoStream(m_stream, transform, );
                m_csstream.Write(DecryptByte, 0, );
                m_csstream.FlushFinalBlock();
                m_strDecrypt = m_stream.ToArray();
                m_stream.Close(); m_stream.Dispose();
                m_csstream.Close(); m_csstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_AESProvider.Clear(); }
            return m_strDecrypt;
        }
        #endregion
        #endregion

    }
}

2. File encryption class

Copy the codeThe code is as follows:

using ;
using System;

namespace Utils
{
    /// <summary>
/// File encryption class
    /// </summary>
    public class FileEncrypt
    {
#region variable
        /// <summary>
/// The number of plain text bytes processed at one time
        /// </summary>
        public static readonly int encryptSize = 10000000;
        /// <summary>
/// The number of ciphertext bytes processed at one time
        /// </summary>
        public static readonly int decryptSize = 10000016;
        #endregion

#region Encrypted files
        /// <summary>
/// Encrypt files
        /// </summary>
        public static void EncryptFile(string path, string pwd, RefreshFileProgress refreshFileProgress)
        {
            try
            {
                if ((path + ".temp")) (path + ".temp");
                using (FileStream fs = new FileStream(path, , ))
                {
                    if ( > 0)
                    {
                        using (FileStream fsnew = new FileStream(path + ".temp", , ))
                        {
                            if ((path + ".temp")) (path + ".temp", );
                            int blockCount = ((int) - 1) / encryptSize + 1;
                            for (int i = 0; i < blockCount; i++)
                            {
                                int size = encryptSize;
                                if (i == blockCount - 1) size = (int)( - i * encryptSize);
                                byte[] bArr = new byte[size];
                                (bArr, 0, size);
                                byte[] result = (bArr, pwd);
                                (result, 0, );
                                ();
refreshFileProgress(blockCount, i + 1); //Update progress
                            }
                            ();
                            ();
                        }
                        ();
                        ();
                        FileAttributes fileAttr = (path);
                        (path, );
                        (path);
                        (path + ".temp", path);
                        (path, fileAttr);
                    }
                }
            }
            catch (Exception ex)
            {
                (path + ".temp");
                throw ex;
            }
        }
        #endregion

#region Decrypts files
        /// <summary>
/// Decrypt the file
        /// </summary>
        public static void DecryptFile(string path, string pwd, RefreshFileProgress refreshFileProgress)
        {
            try
            {
                if ((path + ".temp")) (path + ".temp");
                using (FileStream fs = new FileStream(path, , ))
                {
                    if ( > 0)
                    {
                        using (FileStream fsnew = new FileStream(path + ".temp", , ))
                        {
                            if ((path + ".temp")) (path + ".temp", );
                            int blockCount = ((int) - 1) / decryptSize + 1;
                            for (int i = 0; i < blockCount; i++)
                            {
                                int size = decryptSize;
                                if (i == blockCount - 1) size = (int)( - i * decryptSize);
                                byte[] bArr = new byte[size];
                                (bArr, 0, size);
                                byte[] result = (bArr, pwd);
                                (result, 0, );
                                ();
refreshFileProgress(blockCount, i + 1); //Update progress
                            }
                            ();
                            ();
                        }
                        ();
                        ();
                        FileAttributes fileAttr = (path);
                        (path, );
                        (path);
                        (path + ".temp", path);
                        (path, fileAttr);
                    }
                }
            }
            catch (Exception ex)
            {
                (path + ".temp");
                throw ex;
            }
        }
        #endregion

    }

    /// <summary>
/// Update file encryption progress
    /// </summary>
    public delegate void RefreshFileProgress(int max, int value);

}

3. Folder encryption class

Copy the codeThe code is as follows:

using System;
using ;
using ;
using ;
using ;
using Utils;

namespace
{
    /// <summary>
/// Folder encryption class
    /// </summary>
    public class DirectoryEncrypt
    {
#region Encrypt all files in folders and their subfolders
        /// <summary>
/// Encrypt all files in folders and their subfolders
        /// </summary>
        public static void EncryptDirectory(string dirPath, string pwd, RefreshDirProgress refreshDirProgress, RefreshFileProgress refreshFileProgress)
        {
            string[] filePaths = (dirPath, "*", );
            for (int i = 0; i < ; i++)
            {
                (filePaths[i], pwd, refreshFileProgress);
                refreshDirProgress(, i + 1);
            }
        }
        #endregion

#region Decrypt all files in folders and their subfolders
        /// <summary>
/// Decrypt all files in folders and their subfolders
        /// </summary>
        public static void DecryptDirectory(string dirPath, string pwd, RefreshDirProgress refreshDirProgress, RefreshFileProgress refreshFileProgress)
        {
            string[] filePaths = (dirPath, "*", );
            for (int i = 0; i < ; i++)
            {
                (filePaths[i], pwd, refreshFileProgress);
                refreshDirProgress(, i + 1);
            }
        }
        #endregion

    }

    /// <summary>
/// Update folder encryption progress
    /// </summary>
    public delegate void RefreshDirProgress(int max, int value);

}

4. Cross-thread access control delegation

Copy the codeThe code is as follows:

using System;
using ;

namespace Utils
{
    /// <summary>
/// Delegation of cross-thread access control
    /// </summary>
    public delegate void InvokeDelegate();

    /// <summary>
/// Cross-thread access control class
    /// </summary>
    public class InvokeUtil
    {
        /// <summary>
/// Cross-thread access control
        /// </summary>
/// <param name="ctrl">Form object</param>
/// <param name="de">Trust</param>
        public static void Invoke(Control ctrl, Delegate de)
        {
            if ()
            {
                (de);
            }
        }
    }
}

5. Documents

Copy the codeThe code is as follows:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using Utils;
using ;
using ;

namespace EncryptFile
{
    public partial class Form1 : Form
    {
#region variable
        /// <summary>
/// The number of plain text bytes processed at one time
        /// </summary>
        public static int encryptSize = 10000000;
        /// <summary>
/// The number of ciphertext bytes processed at one time
        /// </summary>
        public static int decryptSize = 10000016;
        #endregion

#region constructor
        public Form1()
        {
            InitializeComponent();
        }
        #endregion

#region Encrypted files
        private void btnEncrypt_Click(object sender, EventArgs e)
        {
#region Verification
            if ( == "")
            {
("Password cannot be empty", "Prompt");
                return;
            }

            if ( == "")
            {
("Confirm the password cannot be empty", "Prompt");
                return;
            }

            if ( != )
            {
("The password entered twice is different", "prompt");
                return;
            }
            #endregion

            if (() == )
            {
                Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj)
                {
                    try
                    {
                        InvokeDelegate invokeDelegate = delegate()
                        {
                            = 0;
                            = "0%";
                            = false;
                            = false;
                            = false;
                            = false;
= "File:" + ;
                            = true;
                            DisableBtns();
                        };
                        (this, invokeDelegate);
                        DateTime t1 = ;
                        (, , RefreshFileProgress);
                        DateTime t2 = ;
                        string t = (t1).("0.00");
if (("Encryption successfully, time taken" + t + "seconds", "prompt") == )
                        {
                            invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            (this, invokeDelegate);
                        }
                    }
                    catch (Exception ex)
                    {
if (("Encryption failed:" + , "Prompt") == )
                        {
                            InvokeDelegate invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            (this, invokeDelegate);
                        }
                    }
                }));
                ();
            }
        }
        #endregion

#region Decrypts files
        private void btnDecrypt_Click(object sender, EventArgs e)
        {
#region Verification
            if ( == "")
            {
("Password cannot be empty", "Prompt");
                return;
            }
            #endregion

            if (() == )
            {
                Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj)
                {
                    try
                    {
                        InvokeDelegate invokeDelegate = delegate()
                        {
                            = 0;
                            = "0%";
                            = false;
                            = false;
                            = false;
                            = false;
= "File:" + ;
                            = true;
                            DisableBtns();
                        };
                        (this, invokeDelegate);
                        DateTime t1 = ;
                        (, , RefreshFileProgress);
                        DateTime t2 = ;
                        string t = (t1).("0.00");
if ((("Decryption successfully, time taken" + t + "seconds", "prompt") == )
                        {
                            invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            (this, invokeDelegate);
                        }
                    }
                    catch (Exception ex)
                    {
if (("Decryption failed:" + , "Prompt") == )
                        {
                            InvokeDelegate invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            (this, invokeDelegate);
                        }
                    }
                }));
                ();
            }
        }
        #endregion

#region folder encryption
        private void btnEncryptDir_Click(object sender, EventArgs e)
        {
#region Verification
            if ( == "")
            {
("Password cannot be empty", "Prompt");
                return;
            }

            if ( == "")
            {
("Confirm the password cannot be empty", "Prompt");
                return;
            }

            if ( != )
            {
("The password entered twice is different", "prompt");
                return;
            }
            #endregion

            if (() == )
            {
if (((("Confirm encrypted folder {0}?", ),
"Tip", ) == )
                {
                    return;
                }

                Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj)
                {
                    try
                    {
                        InvokeDelegate invokeDelegate = delegate()
                        {
                            = 0;
                            = "0%";
                            = 0;
                            = "0%";
                            = true;
                            = true;
                            = false;
                            = false;
= "Folder:" + ;
                            = true;
                            DisableBtns();
                        };
                        (this, invokeDelegate);
                        DateTime t1 = ;
                        (, , RefreshDirProgress, RefreshFileProgress);
                        DateTime t2 = ;
                        string t = (t1).("0.00");
if (("Encryption successfully, time taken" + t + "seconds", "prompt") == )
                        {
                            invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            (this, invokeDelegate);
                        }
                    }
                    catch (Exception ex)
                    {
if (("Encryption failed:" + , "Prompt") == )
                        {
                            InvokeDelegate invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            (this, invokeDelegate);
                        }
                    }
                }));
                ();
            }
        }
        #endregion

#region folder decryption
        private void btnDecryptDir_Click(object sender, EventArgs e)
        {
#region Verification
            if ( == "")
            {
("Password cannot be empty", "Prompt");
                return;
            }
            #endregion

            if (() == )
            {
if (((("Confirm decrypting folder {0}?", ),
"Tip", ) == )
                {
                    return;
                }

                Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj)
                {
                    try
                    {
                        InvokeDelegate invokeDelegate = delegate()
                        {
                            = 0;
                            = "0%";
                            = 0;
                            = "0%";
                            = true;
                            = true;
                            = false;
                            = false;
= "Folder:" + ;
                            = true;
                            DisableBtns();
                        };
                        (this, invokeDelegate);
                        DateTime t1 = ;
                        (, , RefreshDirProgress, RefreshFileProgress);
                        DateTime t2 = ;
                        string t = (t1).("0.00");
if ((("Decryption successfully, time taken" + t + "seconds", "prompt") == )
                        {
                            invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            (this, invokeDelegate);
                        }
                    }
                    catch (Exception ex)
                    {
if (("Decryption failed:" + , "Prompt") == )
                        {
                            InvokeDelegate invokeDelegate = delegate()
                            {
                                EnableBtns();
                            };
                            (this, invokeDelegate);
                        }
                    }
                }));
                ();
            }
        }
        #endregion

#region Update file encryption progress
        /// <summary>
/// Update file encryption progress
        /// </summary>
        public void RefreshFileProgress(int max, int value)
        {
            InvokeDelegate invokeDelegate = delegate()
            {
                if (max > 1)
                {
                    = true;
                    = true;
                }
                else
                {
                    = false;
                    = false;
                }
                = max;
                = value;
                = value * 100 / max + "%";
            };
            (this, invokeDelegate);
        }
        #endregion

#region Update folder encryption progress
        /// <summary>
/// Update folder encryption progress
        /// </summary>
        public void RefreshDirProgress(int max, int value)
        {
            InvokeDelegate invokeDelegate = delegate()
            {
                = max;
                = value;
                = value * 100 / max + "%";
            };
            (this, invokeDelegate);
        }
        #endregion

#region Show password
        private void cbxShowPwd_CheckedChanged(object sender, EventArgs e)
        {
            if ()
            {
                = default(char);
                = default(char);
            }
            else
            {
                = '*';
                = '*';
            }
        }
        #endregion

#region Close form event
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if ()
            {
("Processing files, please wait...", "Prompt");
                = true;
            }
        }
        #endregion

#region Control button status
        /// <summary>
/// Disable button
        /// </summary>
        public void DisableBtns()
        {
            = true;
            = false;
            = false;
            = false;
            = false;
        }
        /// <summary>
/// Enable button
        /// </summary>
        public void EnableBtns()
        {
            = false;
            = false;
            = true;
            = true;
            = true;
            = true;
        }
        #endregion

    }
}

Click here for the full example codeDownload this site

I hope this article will be helpful to everyone's C# programming.