/// <summary>
/// 加密文件
/// </summary>
/// <param name="inFile">待加密文件</param>
/// <param name="outFile">加密后输入文件</param>
/// <param name="password">加密密码</param>
public static void EncryptFile(string inFile, string outPath, string password)
{
try
{
String md5 = GetMD5HashFromFile(inFile).ToUpper();
String outFile = Path.Combine(outPath, md5 + ".LDATA");
if (File.Exists(outFile))
{
return;
}
String fileName = Path.GetFileName(inFile);
byte[] byts = Encoding.UTF8.GetBytes(fileName);
byte[] blen = System.BitConverter.GetBytes(byts.Length);
int toplen = byts.Length + blen.Length + 1;
byte[] tops = new byte[toplen];
tops[0] = (byte)blen.Length;
Array.Copy(blen, 0, tops, 1, blen.Length);
Array.Copy(byts, 0, tops, blen.Length + 1, byts.Length);
using (FileStream fin = File.OpenRead(inFile),fout = File.OpenWrite(outFile))
{
long lSize = fin.Length; // 输入文件长度
int size = (int)lSize;
byte[] bytes = new byte[BUFFER_SIZE]; // 缓存
int read = -1; // 输入文件读取数量
int value = 0;
// 获取IV和salt
byte[] IV = GenerateRandomBytes(16);
byte[] salt = GenerateRandomBytes(16);
// 创建加密对象
SymmetricAlgorithm sma = Common.CreateRijndael(password, salt);
sma.IV = IV;
// 在输出文件开始部分写入文件信息
fout.Write(tops, 0, tops.Length);
// 在输出文件开始部分写入IV和salt
fout.Write(IV, 0, IV.Length);
fout.Write(salt, 0, salt.Length);
// 创建散列加密
HashAlgorithm hasher = SHA256.Create();
using (CryptoStream cout = new CryptoStream(fout, sma.CreateEncryptor(), CryptoStreamMode.Write),
chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
{
BinaryWriter bw = new BinaryWriter(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();
}
}
}
catch (Exception Err)
{
Console.WriteLine("加密异常:" + Err.Message);
}
}
这段代码主要做了3个事情:
1.对文件按照指定密码进行加密
2.将文件重命为.LDATA后缀名的文
3.获取文件的MD5值,并重命名文件,这个很重要在很多场合,可以排除重复文件