Csharp/C#教程:C#加密解密文件小工具实现代码分享

DebugLZQ在网上搜索相关文件加密的程序,发现给出的基本都是针对“字符创”、“文本”的加密与解密。对视频文件、图片等一般文件的加密解密程序少之又少,故写下此文,实现一个对一般文件进行加密的小工具。
  程序的主要功能是:用户通过文件选择框选择要加密的文件-》输入密码进行加密;选择加密后的文件,输入密码进行解密。
  程序的主界面如下:

C#加密解密文件小工具实现代码

三个按钮的Click事件处理程序如下:
代码如下:
privatevoidbtnSelectFile_Click(objectsender,EventArgse)
{
if(openFileDialog1.ShowDialog()==System.Windows.Forms.DialogResult.OK)
{
txtFileName.Text=openFileDialog1.FileName;
}
}
privatevoidbtnEncryptFile_Click(objectsender,EventArgse)
{
stringinFile=txtFileName.Text;
stringoutFile=inFile+”.dat”;
stringpassword=txtPassword.Text;
DESFile.DESFileClass.EncryptFile(inFile,outFile,password);//加密文件
//删除加密前的文件
File.Delete(inFile);
txtFileName.Text=string.Empty;
MessageBox.Show(“加密成功”);
}
privatevoidbtnDecryptFile_Click(objectsender,EventArgse)
{
stringinFile=txtFileName.Text;
stringoutFile=inFile.Substring(0,inFile.Length-4);
stringpassword=txtPassword.Text;
DESFile.DESFileClass.DecryptFile(inFile,outFile,password);//解密文件
//删除解密前的文件
File.Delete(inFile);
txtFileName.Text=string.Empty;
MessageBox.Show(“解密成功”);
}

加密解密的Help文件源码如下:
代码如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Security.Cryptography;
usingSystem.IO;
namespaceDESFile
{
///<summary>
///异常处理类
///</summary>
publicclassCryptoHelpException:ApplicationException
{
publicCryptoHelpException(stringmsg):base(msg){}
}
///<summary>
///CryptHelp
///</summary>
publicclassDESFileClass
{
privateconstulongFC_TAG=0xFC010203040506CF;
privateconstintBUFFER_SIZE=128*1024;
///<summary>
///检验两个Byte数组是否相同
///</summary>
///<paramname=”b1″>Byte数组</param>
///<paramname=”b2″>Byte数组</param>
///<returns>true-相等</returns>
privatestaticboolCheckByteArrays(byte[]b1,byte[]b2)
{
if(b1.Length==b2.Length)
{
for(inti=0;i<b1.Length;++i)
{
if(b1[i]!=b2[i])
returnfalse;
}
returntrue;
}
returnfalse;
}
///<summary>
///创建DebugLZQ,https://www.cnblogs.com/DebugLZQ
///</summary>
///<paramname=”password”>密码</param>
///<paramname=”salt”></param>
///<returns>加密对象</returns>
privatestaticSymmetricAlgorithmCreateRijndael(stringpassword,byte[]salt)
{
PasswordDeriveBytespdb=newPasswordDeriveBytes(password,salt,”SHA256″,1000);
SymmetricAlgorithmsma=Rijndael.Create();
sma.KeySize=256;
sma.Key=pdb.GetBytes(32);
sma.Padding=PaddingMode.PKCS7;
returnsma;
}
///<summary>
///加密文件随机数生成
///</summary>
privatestaticRandomNumberGeneratorrand=newRNGCryptoServiceProvider();
///<summary>
///生成指定长度的随机Byte数组
///</summary>
///<paramname=”count”>Byte数组长度</param>
///<returns>随机Byte数组</returns>
privatestaticbyte[]GenerateRandomBytes(intcount)
{
byte[]bytes=newbyte[count];
rand.GetBytes(bytes);
returnbytes;
}
///<summary>
///加密文件
///</summary>
///<paramname=”inFile”>待加密文件</param>
///<paramname=”outFile”>加密后输入文件</param>
///<paramname=”password”>加密密码</param>
publicstaticvoidEncryptFile(stringinFile,stringoutFile,stringpassword)
{
using(FileStreamfin=File.OpenRead(inFile),
fout=File.OpenWrite(outFile))
{
longlSize=fin.Length;//输入文件长度
intsize=(int)lSize;
byte[]bytes=newbyte[BUFFER_SIZE];//缓存
intread=-1;//输入文件读取数量
intvalue=0;
//获取IV和salt
byte[]IV=GenerateRandomBytes(16);
byte[]salt=GenerateRandomBytes(16);
//创建加密对象
SymmetricAlgorithmsma=DESFileClass.CreateRijndael(password,salt);
sma.IV=IV;
//在输出文件开始部分写入IV和sal t
fout.Write(IV,0,IV.Length);
fout.Write(salt,0,salt.Length);
//创建散列加密
HashAlgorithmhasher=SHA256.Create();
using(CryptoStreamcout=newCryptoStream(fout,sma.CreateEncryptor(),CryptoStreamMode.Write),
chash=newCryptoStream(Stream.Null,hasher,CryptoStreamMode.Write))
{
BinaryWriterbw=newBinaryWriter(cout);
bw.Write(lSize);
bw.Write(FC_TAG);
//读写字节块到加密流缓冲区
while((read=fin.Read(bytes,0,bytes.Length))!=0)
{
cout.Write(bytes,0,read);
chash.Write(bytes,0,read);
value+=read;
}
//关闭加密流
chash.Flush();
chash.Close();
//读取散列
byte[]hash=hasher.Hash;
//输入文件写入散列
cout.Write(hash,0,hash.Length);
//关闭文件流
cout.Flush();
cout.Close();
}
}
}
///<summary>
///解密文件
///</summary>
///<paramname=”inFile”>待解密文件</param>
///<paramname=”outFile”>解密后输出文件</param>
///<paramname=”password”>解密密码</param>
publicstaticvoidDecryptFile(stringinFile,stringoutFile,stringpassword)
{
//创建打开文件流
using(FileStreamfin=File.OpenRead(inFile),
fout=File.OpenWrite(outFile))
{
intsize=(int)fin.Length;
byte[]bytes=newbyte[BUFFER_SIZE];
intread=-1;
intvalue=0;
intoutValue=0;
byte[]IV=newbyte[16];
fin.Read(IV,0,16);
byte[]salt=newbyte[16];
fin.Read(salt,0,16);
SymmetricAlgorithmsma=DESFileClass.CreateRijndael(password,salt);
sma.IV=IV;
value=32;
longlSize=-1;
//创建散列对象,校验文件
HashAlgorithmhasher=SHA256.Create();
using(CryptoStreamcin=newCryptoStream(fin,sma.CreateDecryptor(),CryptoStreamMode.Read),
chash=newCryptoStream(Stream.Null,hasher,CryptoStreamMode.Write))
{
//读取文件长度
BinaryReaderbr=newBinaryReader(cin);
lSize=br.ReadInt64();
ulongtag=br.ReadUInt64();
if(FC_TAG!=tag)
thrownewCryptoHelpException(“文件被破坏”);
longnumReads=lSize/BUFFER_SIZE;
longslack=(long)lSize%BUFFER_SIZE;
for(inti=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;
//获取比较和旧的散列对象
byte[]oldHash=newbyte[hasher.HashSize/8];
read=cin.Read(oldHash,0,oldHash.Length);
if((oldHash.Length!=read)||(!CheckByteArrays(oldHash,curHash)))
thrownewCryptoHelpException(“文件被破坏”);
}
if(outValue!=lSize)
thrownewCryptoHelpException(“文件大小不匹配”);
}
}
}
}

加密/解密结果:
以加密D盘下的1.avi为例,加密后的文件为1.avi.dat,即使重命名回1.avi文件依然无法打开(文件被加密)。

C#加密解密文件小工具实现代码

输入密码进行解密后,文件恢复解密,可以顺利打开~

C#加密解密文件小工具实现代码

您可能感兴趣的文章:C#实现获取设置IP地址小工具C#字符串处理小工具c#实现一个超实用的证件照换底色小工具(附源码)

标签: 加密解密 工具 加密

C++中的常对象与常对象成员详解

C++中指向对象的常指针与指向常对象的指针详解

上述就是C#学习教程:C#加密解密文件小工具实现代码分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/904298.html

(0)
上一篇 2021年10月21日
下一篇 2021年10月21日

精彩推荐