C file encryption method summary
- 2020-11-26 18:58:41
- OfStack
An example of this article summarizes the C# file encryption method. Share to everybody for everybody reference. Specific implementation methods are as follows:
1. AES encryption class
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Utils
{
/// <summary>
/// AES Encryption to decrypt
/// </summary>
public class AES
{
#region encryption
#region Encrypted string
/// <summary>
/// AES encryption ( Advanced encryption standard, yes 1 Generation of encryption algorithm standard, fast speed, high security level, at present AES The standard 1 An implementation is Rijndael algorithm )
/// </summary>
/// <param name="EncryptString"> Ciphertext to be encrypted </param>
/// <param name="EncryptKey"> Encryption key </param>
public static string AESEncrypt(string EncryptString, string EncryptKey)
{
return Convert.ToBase64String(AESEncrypt(Encoding.Default.GetBytes(EncryptString), EncryptKey));
}
#endregion
#region Encrypted byte array
/// <summary>
/// AES encryption ( Advanced encryption standard, yes 1 Generation of encryption algorithm standard, fast speed, high security level, at present AES The standard 1 An implementation is Rijndael algorithm )
/// </summary>
/// <param name="EncryptString"> Ciphertext to be encrypted </param>
/// <param name="EncryptKey"> Encryption key </param>
public static byte[] AESEncrypt(byte[] EncryptByte, string EncryptKey)
{
if (EncryptByte.Length == 0) { throw (new Exception(" Clear text must not be empty ")); }
if (string.IsNullOrEmpty(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 = Rijndael.Create();
try
{
MemoryStream m_stream = new MemoryStream();
PasswordDeriveBytes pdb = new PasswordDeriveBytes(EncryptKey, m_salt);
ICryptoTransform transform = m_AESProvider.CreateEncryptor(pdb.GetBytes(32), m_btIV);
CryptoStream m_csstream = new CryptoStream(m_stream, transform, CryptoStreamMode.Write);
m_csstream.Write(EncryptByte, 0, EncryptByte.Length);
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, yes 1 Generation of encryption algorithm standard, fast speed, high security level, at present AES The standard 1 An implementation is Rijndael algorithm )
/// </summary>
/// <param name="DecryptString"> Ciphertext to be decrypted </param>
/// <param name="DecryptKey"> The decryption key </param>
public static string AESDecrypt(string DecryptString, string DecryptKey)
{
return Convert.ToBase64String(AESDecrypt(Encoding.Default.GetBytes(DecryptString), DecryptKey));
}
#endregion
#region Decrypt byte array
/// <summary>
/// AES decryption ( Advanced encryption standard, yes 1 Generation of encryption algorithm standard, fast speed, high security level, at present AES The standard 1 An implementation is Rijndael algorithm )
/// </summary>
/// <param name="DecryptString"> Ciphertext to be decrypted </param>
/// <param name="DecryptKey"> The decryption key </param>
public static byte[] AESDecrypt(byte[] DecryptByte, string DecryptKey)
{
if (DecryptByte.Length == 0) { throw (new Exception(" Ciphertext must not be empty ")); }
if (string.IsNullOrEmpty(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 = Rijndael.Create();
try
{
MemoryStream m_stream = new MemoryStream();
PasswordDeriveBytes pdb = new PasswordDeriveBytes(DecryptKey, m_salt);
ICryptoTransform transform = m_AESProvider.CreateDecryptor(pdb.GetBytes(32), m_btIV);
CryptoStream m_csstream = new CryptoStream(m_stream, transform, CryptoStreamMode.Write);
m_csstream.Write(DecryptByte, 0, DecryptByte.Length);
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
using System.IO;
using System;
namespace Utils
{
/// <summary>
/// File encryption class
/// </summary>
public class FileEncrypt
{
#region variable
/// <summary>
/// 1 The number of clear bytes processed
/// </summary>
public static readonly int encryptSize = 10000000;
/// <summary>
/// 1 The number of ciphertext bytes processed
/// </summary>
public static readonly int decryptSize = 10000016;
#endregion
#region Encrypted file
/// <summary>
/// Encrypted file
/// </summary>
public static void EncryptFile(string path, string pwd, RefreshFileProgress refreshFileProgress)
{
try
{
if (File.Exists(path + ".temp")) File.Delete(path + ".temp");
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
if (fs.Length > 0)
{
using (FileStream fsnew = new FileStream(path + ".temp", FileMode.OpenOrCreate, FileAccess.Write))
{
if (File.Exists(path + ".temp")) File.SetAttributes(path + ".temp", FileAttributes.Hidden);
int blockCount = ((int)fs.Length - 1) / encryptSize + 1;
for (int i = 0; i < blockCount; i++)
{
int size = encryptSize;
if (i == blockCount - 1) size = (int)(fs.Length - i * encryptSize);
byte[] bArr = new byte[size];
fs.Read(bArr, 0, size);
byte[] result = AES.AESEncrypt(bArr, pwd);
fsnew.Write(result, 0, result.Length);
fsnew.Flush();
refreshFileProgress(blockCount, i + 1); // Update progress
}
fsnew.Close();
fsnew.Dispose();
}
fs.Close();
fs.Dispose();
FileAttributes fileAttr = File.GetAttributes(path);
File.SetAttributes(path, FileAttributes.Archive);
File.Delete(path);
File.Move(path + ".temp", path);
File.SetAttributes(path, fileAttr);
}
}
}
catch (Exception ex)
{
File.Delete(path + ".temp");
throw ex;
}
}
#endregion
#region Declassified documents
/// <summary>
/// Declassified documents
/// </summary>
public static void DecryptFile(string path, string pwd, RefreshFileProgress refreshFileProgress)
{
try
{
if (File.Exists(path + ".temp")) File.Delete(path + ".temp");
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
if (fs.Length > 0)
{
using (FileStream fsnew = new FileStream(path + ".temp", FileMode.OpenOrCreate, FileAccess.Write))
{
if (File.Exists(path + ".temp")) File.SetAttributes(path + ".temp", FileAttributes.Hidden);
int blockCount = ((int)fs.Length - 1) / decryptSize + 1;
for (int i = 0; i < blockCount; i++)
{
int size = decryptSize;
if (i == blockCount - 1) size = (int)(fs.Length - i * decryptSize);
byte[] bArr = new byte[size];
fs.Read(bArr, 0, size);
byte[] result = AES.AESDecrypt(bArr, pwd);
fsnew.Write(result, 0, result.Length);
fsnew.Flush();
refreshFileProgress(blockCount, i + 1); // Update progress
}
fsnew.Close();
fsnew.Dispose();
}
fs.Close();
fs.Dispose();
FileAttributes fileAttr = File.GetAttributes(path);
File.SetAttributes(path, FileAttributes.Archive);
File.Delete(path);
File.Move(path + ".temp", path);
File.SetAttributes(path, fileAttr);
}
}
}
catch (Exception ex)
{
File.Delete(path + ".temp");
throw ex;
}
}
#endregion
}
/// <summary>
/// Update file encryption progress
/// </summary>
public delegate void RefreshFileProgress(int max, int value);
}
3, folder encryption class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Utils;
namespace EncryptFile.Utils
{
/// <summary>
/// Folder encryption class
/// </summary>
public class DirectoryEncrypt
{
#region Encrypt all files in the folder and its subfolders
/// <summary>
/// Encrypt all files in the folder and its subfolders
/// </summary>
public static void EncryptDirectory(string dirPath, string pwd, RefreshDirProgress refreshDirProgress, RefreshFileProgress refreshFileProgress)
{
string[] filePaths = Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories);
for (int i = 0; i < filePaths.Length; i++)
{
FileEncrypt.EncryptFile(filePaths[i], pwd, refreshFileProgress);
refreshDirProgress(filePaths.Length, i + 1);
}
}
#endregion
#region Decrypt all files in the folder and its subfolders
/// <summary>
/// Decrypt all files in the folder and its subfolders
/// </summary>
public static void DecryptDirectory(string dirPath, string pwd, RefreshDirProgress refreshDirProgress, RefreshFileProgress refreshFileProgress)
{
string[] filePaths = Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories);
for (int i = 0; i < filePaths.Length; i++)
{
FileEncrypt.DecryptFile(filePaths[i], pwd, refreshFileProgress);
refreshDirProgress(filePaths.Length, i + 1);
}
}
#endregion
}
/// <summary>
/// Update folder encryption progress
/// </summary>
public delegate void RefreshDirProgress(int max, int value);
}
4, cross-thread access control delegate
using System;
using System.Windows.Forms;
namespace Utils
{
/// <summary>
/// Access the control's delegate across threads
/// </summary>
public delegate void InvokeDelegate();
/// <summary>
/// Access control classes across threads
/// </summary>
public class InvokeUtil
{
/// <summary>
/// Controls are accessed across threads
/// </summary>
/// <param name="ctrl">Form object </param>
/// <param name="de"> entrust </param>
public static void Invoke(Control ctrl, Delegate de)
{
if (ctrl.IsHandleCreated)
{
ctrl.BeginInvoke(de);
}
}
}
}
5. Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Utils;
using System.Threading;
using EncryptFile.Utils;
namespace EncryptFile
{
public partial class Form1 : Form
{
#region variable
/// <summary>
/// 1 The number of clear bytes processed
/// </summary>
public static int encryptSize = 10000000;
/// <summary>
/// 1 The number of ciphertext bytes processed
/// </summary>
public static int decryptSize = 10000016;
#endregion
#region The constructor
public Form1()
{
InitializeComponent();
}
#endregion
#region Encrypted file
private void btnEncrypt_Click(object sender, EventArgs e)
{
#region validation
if (txtPwd.Text == "")
{
MessageBox.Show(" The password cannot be empty ", " prompt ");
return;
}
if (txtPwdCfm.Text == "")
{
MessageBox.Show(" Confirm that the password cannot be empty ", " prompt ");
return;
}
if (txtPwdCfm.Text != txtPwd.Text)
{
MessageBox.Show(" The two passwords are different ", " prompt ");
return;
}
#endregion
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj)
{
try
{
InvokeDelegate invokeDelegate = delegate()
{
pbFile.Value = 0;
lblProgressFile.Text = "0%";
pbDir.Visible = false;
lblProgressDir.Visible = false;
pbFile.Visible = false;
lblProgressFile.Visible = false;
lblShowPath.Text = " File: " + openFileDialog1.FileName;
lblShowPath.Visible = true;
DisableBtns();
};
InvokeUtil.Invoke(this, invokeDelegate);
DateTime t1 = DateTime.Now;
FileEncrypt.EncryptFile(openFileDialog1.FileName, txtPwd.Text, RefreshFileProgress);
DateTime t2 = DateTime.Now;
string t = t2.Subtract(t1).TotalSeconds.ToString("0.00");
if (MessageBox.Show(" Encryption successful, time consuming " + t + " seconds ", " prompt ") == DialogResult.OK)
{
invokeDelegate = delegate()
{
EnableBtns();
};
InvokeUtil.Invoke(this, invokeDelegate);
}
}
catch (Exception ex)
{
if (MessageBox.Show(" Encryption failed: " + ex.Message, " prompt ") == DialogResult.OK)
{
InvokeDelegate invokeDelegate = delegate()
{
EnableBtns();
};
InvokeUtil.Invoke(this, invokeDelegate);
}
}
}));
thread.Start();
}
}
#endregion
#region Declassified documents
private void btnDecrypt_Click(object sender, EventArgs e)
{
#region validation
if (txtPwd.Text == "")
{
MessageBox.Show(" The password cannot be empty ", " prompt ");
return;
}
#endregion
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj)
{
try
{
InvokeDelegate invokeDelegate = delegate()
{
pbFile.Value = 0;
lblProgressFile.Text = "0%";
pbDir.Visible = false;
lblProgressDir.Visible = false;
pbFile.Visible = false;
lblProgressFile.Visible = false;
lblShowPath.Text = " File: " + openFileDialog1.FileName;
lblShowPath.Visible = true;
DisableBtns();
};
InvokeUtil.Invoke(this, invokeDelegate);
DateTime t1 = DateTime.Now;
FileEncrypt.DecryptFile(openFileDialog1.FileName, txtPwd.Text, RefreshFileProgress);
DateTime t2 = DateTime.Now;
string t = t2.Subtract(t1).TotalSeconds.ToString("0.00");
if (MessageBox.Show(" Decryption successful, time consuming " + t + " seconds ", " prompt ") == DialogResult.OK)
{
invokeDelegate = delegate()
{
EnableBtns();
};
InvokeUtil.Invoke(this, invokeDelegate);
}
}
catch (Exception ex)
{
if (MessageBox.Show(" Decryption failed: " + ex.Message, " prompt ") == DialogResult.OK)
{
InvokeDelegate invokeDelegate = delegate()
{
EnableBtns();
};
InvokeUtil.Invoke(this, invokeDelegate);
}
}
}));
thread.Start();
}
}
#endregion
#region Folder encryption
private void btnEncryptDir_Click(object sender, EventArgs e)
{
#region validation
if (txtPwd.Text == "")
{
MessageBox.Show(" The password cannot be empty ", " prompt ");
return;
}
if (txtPwdCfm.Text == "")
{
MessageBox.Show(" Confirm that the password cannot be empty ", " prompt ");
return;
}
if (txtPwdCfm.Text != txtPwd.Text)
{
MessageBox.Show(" The two passwords are different ", " prompt ");
return;
}
#endregion
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
if (MessageBox.Show(string.Format(" Determine the encrypted folder {0} ? ", folderBrowserDialog1.SelectedPath),
" prompt ", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
{
return;
}
Thread thread = new Thread(new ParameterizedThreadStart(delegate(object obj)
{
try
{
InvokeDelegate invokeDelegate = delegate()
{
pbDir.Value = 0;
lblProgressDir.Text = "0%";
pbFile.Value = 0;
lblProgressFile.Text = "0%";
pbDir.Visible = true;
lblProgressDir.Visible = true;
pbFile.Visible = false;
lblProgressFile.Visible = false;
lblShowPath.Text = " Folders: " + folderBrowserDialog1.SelectedPath;
lblShowPath.Visible = true;
DisableBtns();
};
InvokeUtil.Invoke(this, invokeDelegate);
DateTime t1 = DateTime.Now;
DirectoryEncrypt.EncryptDirectory(folderBrowserDialog1.SelectedPath, txtPwd.Text, RefreshDirProgress, RefreshFileProgress);
DateTime t2 = DateTime.Now;
string t = t2.Subtract(t1).TotalSeconds.ToString("0.00");
if (MessageBox.Show(" Encryption successful, time consuming " + t + " seconds ", " prompt ") == DialogResult.OK)
{
invokeDelegate = delegate()
{
EnableBtns();
};
InvokeUtil.Invoke(this, invokeDelegate);
}
}
catch (Exception ex)
{
if (MessageBox.Show(" Encryption failed :" + ex.Message, " prompt ") == DialogResult.OK)
{
InvokeDelegate invokeDelegate = delegate()
{
EnableBtns();
};
InvokeUtil.Invoke(this, invokeDelegate);
}
}
}));
thread.Start();
}
}
#endregion
#region Folder decryption
private void btnDecryptDir_Click(object sender, EventArgs e)
{
#region validation
if (txtPwd.Text == "")
{
MessageBox.Show(" The password cannot be empty ", " prompt ");
return;
}
#endregion