FileEncryptTool.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. //************************************************************************
  2. // author: yuzhengyang
  3. // date: 2017.6.8 - 2017.6.16
  4. // desc: 文件加密工具
  5. // Copyright (c) yuzhengyang. All rights reserved.
  6. //************************************************************************
  7. using Azylee.Core.DataUtils.EncryptUtils;
  8. using Azylee.Core.DelegateUtils.ProcessDelegateUtils;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Text;
  14. namespace Azylee.Core.IOUtils.FileUtils
  15. {
  16. /// <summary>
  17. /// 文件加密工具
  18. /// </summary>
  19. public class FileEncryptTool
  20. {
  21. const string FileType = "Y.Utils.FileEncrypt";//文件类型 禁止修改长度(19位)
  22. const string FileVersion = "100001";//类型的版本 禁止修改长度(6位)
  23. private static int FileBuffer = 1024 * 1024;
  24. public static string FileExt = ".fmencrypt";
  25. /// <summary>
  26. /// 文件加密
  27. /// </summary>
  28. /// <param name="srcFile">源文件</param>
  29. /// <param name="dstFile">目标文件</param>
  30. /// <param name="password">加密密码</param>
  31. /// <param name="progress">回调进度</param>
  32. /// <param name="overwrite">是否覆盖已有目标文件</param>
  33. /// <returns>
  34. /// >0:操作成功(操作共计秒数)
  35. /// -11:要加密的文件不存在
  36. /// -12:加密后的目标文件已存在
  37. /// -404:未知错误,操作失败
  38. /// </returns>
  39. public static int Encrypt(string srcFile, string dstFile, string password, ProgressDelegate.ProgressHandler progress = null, object sender = null, bool overwrite = true)
  40. {
  41. DateTime beginTime = DateTime.Now;
  42. if (!File.Exists(srcFile)) return -11; //要加密的文件不存在
  43. if (File.Exists(dstFile) && !overwrite) return -12;//加密后的目标文件已存在
  44. string fmtPwd = AesTool.FmtPassword(password);
  45. string pwdMd5 = MD5Tool.Encrypt(MD5Tool.Encrypt(fmtPwd));
  46. string md5 = FileTool.GetMD5(srcFile);
  47. using (FileStream fsRead = new FileStream(srcFile, FileMode.Open))
  48. {
  49. using (FileStream fsWrite = new FileStream(dstFile, FileMode.Create))
  50. {
  51. try
  52. {
  53. //写入文件类型标识和版本号
  54. byte[] filetypeandversion = Encoding.Default.GetBytes(FileType + FileVersion);
  55. fsWrite.Write(filetypeandversion, 0, filetypeandversion.Length);
  56. //文件头部数据定义
  57. List<byte[]> headdata = new List<byte[]>()
  58. {
  59. Encoding.Default.GetBytes(FileType),
  60. Encoding.Default.GetBytes(md5),
  61. Encoding.Default.GetBytes(AesTool.Encrypt(fmtPwd,AesTool.DefaultPassword)),
  62. Encoding.Default.GetBytes(pwdMd5),
  63. Encoding.Default.GetBytes(DateTime.Now.ToString())
  64. };
  65. //写入头部信息个数
  66. byte[] count = BitConverter.GetBytes(headdata.Count);
  67. fsWrite.Write(count, 0, count.Length);
  68. //写入各部分长度
  69. for (int i = 0; i < headdata.Count; i++)
  70. {
  71. byte[] length = BitConverter.GetBytes(headdata[i].Length);
  72. fsWrite.Write(length, 0, length.Length);
  73. }
  74. //写入各部分数据
  75. for (int i = 0; i < headdata.Count; i++)
  76. {
  77. fsWrite.Write(headdata[i], 0, headdata[i].Length);
  78. }
  79. //写入文件源数据
  80. int readCount = 0;
  81. byte[] buffer = new byte[FileBuffer];
  82. while ((readCount = fsRead.Read(buffer, 0, buffer.Length)) > 0)
  83. {
  84. if (readCount != buffer.Length)
  85. {
  86. byte[] temp = new byte[readCount];
  87. Buffer.BlockCopy(buffer, 0, temp, 0, readCount);
  88. byte[] enbyte = AesTool.Encrypt(temp, fmtPwd);
  89. fsWrite.Write(enbyte, 0, enbyte.Length);
  90. }
  91. else
  92. {
  93. byte[] enbyte = AesTool.Encrypt(buffer, fmtPwd);
  94. fsWrite.Write(enbyte, 0, enbyte.Length);
  95. }
  96. progress?.Invoke(sender, new ProgressEventArgs(fsRead.Position, fsRead.Length));
  97. }
  98. return (int)Math.Ceiling((DateTime.Now - beginTime).TotalSeconds);//操作成功
  99. }
  100. catch (Exception e) { }
  101. }
  102. //加密失败后,删除加密的文件
  103. try { File.Delete(dstFile); } catch (Exception e) { }
  104. }
  105. return -404;//未知错误,操作失败
  106. }
  107. /// <summary>
  108. /// 文件解密
  109. /// </summary>
  110. /// <param name="srcFile">源文件</param>
  111. /// <param name="dstFile">目标文件</param>
  112. /// <param name="password">解密密码</param>
  113. /// <param name="progress">回调进度</param>
  114. /// <param name="overwrite">是否覆盖已有目标文件</param>
  115. /// <returns>
  116. /// >0:操作成功(操作共计秒数)
  117. /// -11:要解密的文件不存在
  118. /// -12:解密后的目标文件已存在
  119. /// -20:文件类型不匹配
  120. /// -30:文件头不长度不吻合
  121. /// -90:解锁密码错误
  122. /// -404:未知错误,操作失败
  123. /// </returns>
  124. public static int Decrypt(string srcFile, string dstFile, string password, ProgressDelegate.ProgressHandler progress = null, object sender = null, bool overwrite = true)
  125. {
  126. DateTime beginTime = DateTime.Now;
  127. if (!File.Exists(srcFile)) return -11;//要解密的文件不存在
  128. if (File.Exists(dstFile) && !overwrite) return -12;//解密后的目标文件已存在
  129. string fmtPwd = AesTool.FmtPassword(password);
  130. string pwdMd5 = MD5Tool.Encrypt(MD5Tool.Encrypt(fmtPwd));
  131. List<string> headdata = new List<string>();
  132. using (FileStream fsRead = new FileStream(srcFile, FileMode.Open))
  133. {
  134. try
  135. {
  136. //读取文件类型标识和版本号
  137. byte[] filetype = Encoding.Default.GetBytes(FileType);
  138. fsRead.Read(filetype, 0, filetype.Length);
  139. string filetypestr = Encoding.Default.GetString(filetype);
  140. byte[] fileversion = Encoding.Default.GetBytes(FileVersion);
  141. fsRead.Read(fileversion, 0, fileversion.Length);
  142. string fileversionstr = Encoding.Default.GetString(fileversion);
  143. if (filetypestr != FileType && fileversionstr != FileVersion) return -20;//文件类型不匹配
  144. //读取头部信息个数
  145. byte[] count = new byte[4];
  146. fsRead.Read(count, 0, count.Length);
  147. int countint = BitConverter.ToInt32(count, 0);
  148. //读取各部分长度和数据
  149. byte[] headlength = new byte[4 * countint];
  150. if (fsRead.Read(headlength, 0, headlength.Length) == headlength.Length)
  151. {
  152. for (int i = 0; i < countint; i++)
  153. {
  154. int datalong = BitConverter.ToInt32(headlength, i * 4);
  155. byte[] tempdata = new byte[datalong];
  156. fsRead.Read(tempdata, 0, datalong);
  157. headdata.Add(Encoding.Default.GetString(tempdata));
  158. }
  159. }
  160. if (headdata.Count < 5) return -30;//文件头不长度不吻合
  161. if (pwdMd5 != headdata[3]) return -90;//解锁密码错误
  162. using (FileStream fsWrite = new FileStream(dstFile, FileMode.Create))
  163. {
  164. int readCount = 0;
  165. byte[] buffer = new byte[FileBuffer + 16];
  166. while ((readCount = fsRead.Read(buffer, 0, buffer.Length)) > 0)
  167. {
  168. if (readCount != buffer.Length)
  169. {
  170. byte[] temp = new byte[readCount];
  171. Buffer.BlockCopy(buffer, 0, temp, 0, readCount);
  172. byte[] debyte = AesTool.Decrypt(temp, fmtPwd);
  173. fsWrite.Write(debyte, 0, debyte.Length);
  174. }
  175. else
  176. {
  177. byte[] debyte = AesTool.Decrypt(buffer, fmtPwd);
  178. fsWrite.Write(debyte, 0, debyte.Length);
  179. }
  180. progress?.Invoke(sender, new ProgressEventArgs(fsRead.Position, fsRead.Length));
  181. }
  182. }
  183. }
  184. catch (Exception e) { }
  185. }
  186. string md5 = FileTool.GetMD5(dstFile);
  187. if (headdata.Count > 1 && md5 == headdata[1])
  188. {
  189. return (int)Math.Ceiling((DateTime.Now - beginTime).TotalSeconds);//操作成功
  190. }
  191. else
  192. {
  193. //解密失败后,删除解密的文件
  194. try { File.Delete(dstFile); } catch (Exception e) { }
  195. }
  196. return -404;//未知错误,操作失败
  197. }
  198. }
  199. }