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);
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 解密
#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);
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、文件加密类
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 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); //更新进度
}
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 解密文件
/// <summary>
/// 解密文件
/// </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); //更新进度
}
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>
/// 更新文件加密进度
/// </summary>
public delegate void refreshfileprogress(int max, int value);
}
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);
}
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);
}
}
}
}
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
}
}
完整实例代码点击此处本站下载。
希望本文所述对大家的c#程序设计有所帮助。