FileEncryptTool.cs 9.9 KB

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