程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 文件加密,文件夾加密

文件加密,文件夾加密

編輯:C#入門知識

文件加密,文件夾加密


代碼:

1、AES加密類

using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace Utils { /// <summary> /// AES加密解密 /// </summary> public class AES { #region 加密 #region 加密字符串 /// <summary> /// AES 加密(高級加密標准,是下一代的加密算法標准,速度快,安全級別高,目前 AES 標准的一個實現是 Rijndael 算法) /// </summary> /// <param name="EncryptString">待加密密文</param> /// <param name="EncryptKey">加密密鑰</param> public static string AESEncrypt(string EncryptString, string EncryptKey) { return Convert.ToBase64String(AESEncrypt(Encoding.Default.GetBytes(EncryptString), EncryptKey)); } #endregion #region 加密字節數組 /// <summary> /// AES 加密(高級加密標准,是下一代的加密算法標准,速度快,安全級別高,目前 AES 標准的一個實現是 Rijndael 算法) /// </summary> /// <param name="EncryptString">待加密密文</param> /// <param name="EncryptKey">加密密鑰</param> public static byte[] AESEncrypt(byte[] EncryptByte, string EncryptKey) { if (EncryptByte.Length == 0) { throw (new Exception("明文不得為空")); } if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密鑰不得為空")); } 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, "SHA256", 1000); CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateEncryptor(pdb.GetBytes(32), m_btIV), 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 解密 #region 解密字符串 /// <summary> /// AES 解密(高級加密標准,是下一代的加密算法標准,速度快,安全級別高,目前 AES 標准的一個實現是 Rijndael 算法) /// </summary> /// <param name="DecryptString">待解密密文</param> /// <param name="DecryptKey">解密密鑰</param> public static string AESDecrypt(string DecryptString, string DecryptKey) { return Convert.ToBase64String(AESDecrypt(Encoding.Default.GetBytes(DecryptString), DecryptKey)); } #endregion #region 解密字節數組 /// <summary> /// AES 解密(高級加密標准,是下一代的加密算法標准,速度快,安全級別高,目前 AES 標准的一個實現是 Rijndael 算法) /// </summary> /// <param name="DecryptString">待解密密文</param> /// <param name="DecryptKey">解密密鑰</param> public static byte[] AESDecrypt(byte[] DecryptByte, string DecryptKey) { if (DecryptByte.Length == 0) { throw (new Exception("密文不得為空")); } if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密鑰不得為空")); } 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, "SHA256", 1000); CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateDecryptor(pdb.GetBytes(32), m_btIV), 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 } } View Code

2、文件加密類

using System.IO; using System; namespace Utils { /// <summary> /// 文件加密類 /// </summary> public class FileEncrypt { #region 變量 /// <summary> /// 一次處理的明文字節數 /// </summary> public static readonly int encryptSize = 10000000; /// <summary> /// 一次處理的密文字節數 /// </summary> public static readonly int decryptSize = 10000016; #endregion #region 加密文件 /// <summary> /// 加密文件 /// </summary> public static void EncryptFile(string path, string pwd, RefreshFileProgress refreshFileProgress) { try { if (File.Exists(path + ".temp")) File.Delete(path + ".temp"); using (FileStream fsTemp = new FileStream(path + ".temp", FileMode.Create)) { fsTemp.Close(); File.SetAttributes(path + ".temp", FileAttributes.Hidden); } using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { if (fs.Length > 0) { int blockCount = ((int)fs.Length - 1) / encryptSize + 1; for (int i = 0; i < blockCount; i++) { fs.Seek(i * encryptSize, SeekOrigin.Begin); 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); using (FileStream fsnew = new FileStream(path + ".temp", FileMode.Append, FileAccess.Write)) { fsnew.Write(result, 0, result.Length); fsnew.Flush(); fsnew.Close(); } refreshFileProgress(blockCount, i + 1); //更新進度 } fs.Close(); File.Delete(path); File.Move(path + ".temp", path); File.SetAttributes(path, FileAttributes.Archive); } } } catch (Exception ex) { File.Delete(path + ".temp"); throw ex; } } #endregion #region 解密文件 /// <summary> /// 解密文件 /// </summary> public static void DecryptFile(string path, string pwd, RefreshFileProgress refreshFileProgress) { try { if (File.Exists(path + ".temp")) File.Delete(path + ".temp"); using (FileStream fsTemp = new FileStream(path + ".temp", FileMode.Create)) { fsTemp.Close(); File.SetAttributes(path + ".temp", FileAttributes.Hidden); } using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { if (fs.Length > 0) { int blockCount = ((int)fs.Length - 1) / decryptSize + 1; for (int i = 0; i < blockCount; i++) { fs.Seek(i * decryptSize, SeekOrigin.Begin); 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); using (FileStream fsnew = new FileStream(path + ".temp", FileMode.Append, FileAccess.Write)) { fsnew.Write(result, 0, result.Length); fsnew.Flush(); fsnew.Close(); } refreshFileProgress(blockCount, i + 1); //更新進度 } fs.Close(); File.Delete(path); File.Move(path + ".temp", path); File.SetAttributes(path, FileAttributes.Archive); } } } catch (Exception ex) { File.Delete(path + ".temp"); throw ex; } } #endregion } /// <summary> /// 更新文件加密進度 /// </summary> public delegate void RefreshFileProgress(int max, int value); } View Code

3、文件夾加密類

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Utils; namespace EncryptFile.Utils { /// <summary> /// 文件夾加密類 /// </summary> public class DirectoryEncrypt { #region 加密文件夾及其子文件夾中的所有文件 /// <summary> /// 加密文件夾及其子文件夾中的所有文件 /// </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 解密文件夾及其子文件夾中的所有文件 /// <summary> /// 解密文件夾及其子文件夾中的所有文件 /// </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> /// 更新文件夾加密進度 /// </summary> public delegate void RefreshDirProgress(int max, int value); } View Code

4、跨線程訪問控制委托

using System; using System.Windows.Forms; namespace Utils { /// <summary> /// 跨線程訪問控件的委托 /// </summary> public delegate void InvokeDelegate(); /// <summary> /// 跨線程訪問控件類 /// </summary> public class InvokeUtil { /// <summary> /// 跨線程訪問控件 /// </summary> /// <param name="ctrl">Form對象</param> /// <param name="de">委托</param> public static void Invoke(Control ctrl, Delegate de) { if (ctrl.IsHandleCreated) { ctrl.BeginInvoke(de); } } } } View Code

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 變量 /// <summary> /// 一次處理的明文字節數 /// </summary> public static int encryptSize = 10000000; /// <summary> /// 一次處理的密文字節數 /// </summary> public static int decryptSize = 10000016; #endregion #region 構造函數 public Form1() { InitializeComponent(); } #endregion #region 加密文件 private void btnEncrypt_Click(object sender, EventArgs e) { #region 驗證 if (txtPwd.Text == "") { MessageBox.Show("密碼不能為空", "提示"); return; } if (txtPwdCfm.Text == "") { MessageBox.Show("確認密碼不能為空", "提示"); return; } if (txtPwdCfm.Text != txtPwd.Text) { MessageBox.Show("兩次輸入的密碼不相同", "提示"); 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 = "文件:" + 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("加密成功,耗時" + t + "秒", "提示") == DialogResult.OK) { invokeDelegate = delegate() { EnableBtns(); }; InvokeUtil.Invoke(this, invokeDelegate); } } catch (Exception ex) { if (MessageBox.Show("加密失敗:" + ex.Message, "提示") == DialogResult.OK) { InvokeDelegate invokeDelegate = delegate() { EnableBtns(); }; InvokeUtil.Invoke(this, invokeDelegate); } } })); thread.Start(); } } #endregion #region 解密文件 private void btnDecrypt_Click(object sender, EventArgs e) { #region 驗證 if (txtPwd.Text == "") { MessageBox.Show("密碼不能為空", "提示"); 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 = "文件:" + 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("解密成功,耗時" + t + "秒", "提示") == DialogResult.OK) { invokeDelegate = delegate() { EnableBtns(); }; InvokeUtil.Invoke(this, invokeDelegate); } } catch (Exception ex) { if (MessageBox.Show("解密失敗:" + ex.Message, "提示") == DialogResult.OK) { InvokeDelegate invokeDelegate = delegate() { EnableBtns(); }; InvokeUtil.Invoke(this, invokeDelegate); } } })); thread.Start(); } } #endregion #region 文件夾加密 private void btnEncryptDir_Click(object sender, EventArgs e) { #region 驗證 if (txtPwd.Text == "") { MessageBox.Show("密碼不能為空", "提示"); return; } if (txtPwdCfm.Text == "") { MessageBox.Show("確認密碼不能為空", "提示"); return; } if (txtPwdCfm.Text != txtPwd.Text) { MessageBox.Show("兩次輸入的密碼不相同", "提示"); return; } #endregion if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { if (MessageBox.Show(string.Format("確定加密文件夾{0}?", folderBrowserDialog1.SelectedPath), "提示", 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 = "文件夾:" + 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("加密成功,耗時" + t + "秒", "提示") == DialogResult.OK) { invokeDelegate = delegate() { EnableBtns(); }; InvokeUtil.Invoke(this, invokeDelegate); } } catch (Exception ex) { if (MessageBox.Show("加密失敗:" + ex.Message, "提示") == DialogResult.OK) { InvokeDelegate invokeDelegate = delegate() { EnableBtns(); }; InvokeUtil.Invoke(this, invokeDelegate); } } })); thread.Start(); } } #endregion #region 文件夾解密 private void btnDecryptDir_Click(object sender, EventArgs e) { #region 驗證 if (txtPwd.Text == "") { MessageBox.Show("密碼不能為空", "提示"); return; } #endregion if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { if (MessageBox.Show(string.Format("確定解密文件夾{0}?", folderBrowserDialog1.SelectedPath), "提示", 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; lblProgressFile.Visible = true; pbFile.Visible = false; lblProgressFile.Visible = false; lblShowPath.Text = "文件夾:" + folderBrowserDialog1.SelectedPath; lblShowPath.Visible = true; DisableBtns(); }; InvokeUtil.Invoke(this, invokeDelegate); DateTime t1 = DateTime.Now; DirectoryEncrypt.DecryptDirectory(folderBrowserDialog1.SelectedPath, txtPwd.Text, RefreshDirProgress, RefreshFileProgress); DateTime t2 = DateTime.Now; string t = t2.Subtract(t1).TotalSeconds.ToString("0.00"); if (MessageBox.Show("解密成功,耗時" + t + "秒", "提示") == DialogResult.OK) { invokeDelegate = delegate() { EnableBtns(); }; InvokeUtil.Invoke(this, invokeDelegate); } } catch (Exception ex) { if (MessageBox.Show("解密失敗:" + ex.Message, "提示") == DialogResult.OK) { InvokeDelegate invokeDelegate = delegate() { EnableBtns(); }; InvokeUtil.Invoke(this, invokeDelegate); } } })); thread.Start(); } } #endregion #region 更新文件加密進度 /// <summary> /// 更新文件加密進度 /// </summary> public void RefreshFileProgress(int max, int value) { InvokeDelegate invokeDelegate = delegate() { if (max > 1) { pbFile.Visible = true; lblProgressFile.Visible = true; } else { pbFile.Visible = false; lblProgressFile.Visible = false; } pbFile.Maximum = max; pbFile.Value = value; lblProgressFile.Text = value * 100 / max + "%"; }; InvokeUtil.Invoke(this, invokeDelegate); } #endregion #region 更新文件夾加密進度 /// <summary> /// 更新文件夾加密進度 /// </summary> public void RefreshDirProgress(int max, int value) { InvokeDelegate invokeDelegate = delegate() { pbDir.Maximum = max; pbDir.Value = value; lblProgressDir.Text = value * 100 / max + "%"; }; InvokeUtil.Invoke(this, invokeDelegate); } #endregion #region 顯示密碼 private void cbxShowPwd_CheckedChanged(object sender, EventArgs e) { if (cbxShowPwd.Checked) { txtPwd.PasswordChar = default(char); txtPwdCfm.PasswordChar = default(char); } else { txtPwd.PasswordChar = '*'; txtPwdCfm.PasswordChar = '*'; } } #endregion #region 關閉窗體事件 private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (progressPanel.Visible) { MessageBox.Show("正在處理文件,請等待…", "提示"); e.Cancel = true; } } #endregion #region 控制按鈕狀態 /// <summary> /// 禁用按鈕 /// </summary> public void DisableBtns() { progressPanel.Visible = true; btnEncrypt.Enabled = false; btnDecrypt.Enabled = false; btnEncryptDir.Enabled = false; btnDecryptDir.Enabled = false; } /// <summary> /// 啟用按鈕 /// </summary> public void EnableBtns() { lblShowPath.Visible = false; progressPanel.Visible = false; btnEncrypt.Enabled = true; btnDecrypt.Enabled = true; btnEncryptDir.Enabled = true; btnDecryptDir.Enabled = true; } #endregion } } View Code

源碼:

源碼下載:下載地址

 


文件夾怎加密

一、加密文件或文件夾
步驟一:打開Windows資源管理器。
步驟二:右鍵單擊要加密的文件或文件夾,然後單擊“屬性”。
步驟三:在“常規”選項卡上,單擊“高級”。選中“加密內容以便保護數據”復選框

在加密過程中還要注意以下五點:
1.打開“Windows 資源管理器”,請單擊“開始→程序→附件”,然後單擊“Windows 資源管理器”。
2.只可以加密NTFS分區卷上的文件和文件夾,FAT分區卷上的文件和文件夾無效。
3.被壓縮的文件或文件夾也可加密。如要加密一個壓縮文件或文件夾,則該文件或文件夾將會被解壓。
4.無法加密標記為“系統”屬性的文件,並且位於systemroot目錄結構中的文件也無法加密。
5.在加密文件夾時,系統將詢問是否要同時加密它的子文件夾。如果選擇是,那它的子文件夾也會被加密,以後所有添加進文件夾中的文件和子文件夾都將在添加時自動加密。

二、解密文件或文件夾
步驟一:打開Windows資源管理器。
步驟二:右鍵單擊加密文件或文件夾,然後單擊“屬性”。
步驟三:在“常規”選項卡上,單擊“高級”。
步驟四:清除“加密內容以便保護數據”復選框。
 

文件夾怎加密

一、加密文件或文件夾
步驟一:打開Windows資源管理器。
步驟二:右鍵單擊要加密的文件或文件夾,然後單擊“屬性”。
步驟三:在“常規”選項卡上,單擊“高級”。選中“加密內容以便保護數據”復選框

在加密過程中還要注意以下五點:
1.打開“Windows 資源管理器”,請單擊“開始→程序→附件”,然後單擊“Windows 資源管理器”。
2.只可以加密NTFS分區卷上的文件和文件夾,FAT分區卷上的文件和文件夾無效。
3.被壓縮的文件或文件夾也可加密。如要加密一個壓縮文件或文件夾,則該文件或文件夾將會被解壓。
4.無法加密標記為“系統”屬性的文件,並且位於systemroot目錄結構中的文件也無法加密。
5.在加密文件夾時,系統將詢問是否要同時加密它的子文件夾。如果選擇是,那它的子文件夾也會被加密,以後所有添加進文件夾中的文件和子文件夾都將在添加時自動加密。

二、解密文件或文件夾
步驟一:打開Windows資源管理器。
步驟二:右鍵單擊加密文件或文件夾,然後單擊“屬性”。
步驟三:在“常規”選項卡上,單擊“高級”。
步驟四:清除“加密內容以便保護數據”復選框。
 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved