You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1116 lines
43 KiB

1 year ago
4 years ago
3 years ago
3 years ago
3 years ago
1 year ago
1 year ago
1 year ago
4 years ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
4 years ago
1 year ago
1 year ago
4 years ago
1 year ago
1 year ago
4 years ago
4 years ago
4 years ago
1 year ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
1 year ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
2 years ago
4 years ago
4 years ago
4 years ago
1 year ago
4 years ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
4 years ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. using Apewer.Internals;
  2. using Externals.Compression.Checksums;
  3. using Externals.Compression.Zip;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.IO.Compression;
  9. using System.Security.Cryptography;
  10. using System.Text;
  11. namespace Apewer
  12. {
  13. /// <summary>二进制。</summary>
  14. public static class BytesUtility
  15. {
  16. /// <summary>空字节数组,每次获取都将创建新的引用。</summary>
  17. public static byte[] Empty = new byte[0];
  18. /// <summary>默认缓冲区大小。</summary>
  19. public const int DefaultBuffer = 4096;
  20. // 预置十六进制字符。
  21. private static readonly char[] UpperHex = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  22. private static readonly char[] LowerHex = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  23. #region ASCII
  24. /// <summary>CRLF</summary>
  25. public static byte[] CRLF { get => new byte[] { 13, 10 }; }
  26. /// <summary>CR</summary>
  27. public static byte[] CR { get => new byte[] { 13 }; }
  28. /// <summary>LF</summary>
  29. public static byte[] LF { get => new byte[] { 10 }; }
  30. #endregion
  31. #region Bytes Array
  32. /// <summary>克隆字节数组。当源为 NULL 时获取零元素字节数组。</summary>
  33. public static byte[] Clone(this byte[] bytes)
  34. {
  35. if (bytes == null) return Empty;
  36. var length = bytes.Length;
  37. if (length < 1) return Empty;
  38. var result = new byte[length];
  39. Buffer.BlockCopy(bytes, 0, result, 0, length);
  40. return result;
  41. }
  42. /// <summary>每个字节取反。</summary>
  43. /// <remarks>value = 255 - value</remarks>
  44. public static byte[] Adverse(this byte[] bytes)
  45. {
  46. if (bytes == null || bytes.LongLength < 1L) return Empty;
  47. var adverse = new byte[bytes.LongLength];
  48. for (var i = 0L; i < bytes.LongLength; i++) adverse[i] = Convert.ToByte(255 - bytes[i]);
  49. return adverse;
  50. }
  51. /// <summary>确定此字节数组实例的开头是否与指定的字节数组匹配。</summary>
  52. public static bool StartsWith(this byte[] bytes, params byte[] head)
  53. {
  54. // 头部为空,视为匹配。
  55. if (head == null) return true;
  56. var length = head.Length;
  57. if (length < 1) return true;
  58. // 样本为空,视为不匹配。
  59. if (bytes == null) return false;
  60. if (bytes.Length < length) return false;
  61. // 对比头部字节。
  62. for (var i = 0; i < length; i++)
  63. {
  64. if (bytes[i] != head[i]) return false;
  65. }
  66. return true;
  67. }
  68. /// <summary>确定此字节数组实例的结尾是否与指定的字节数组匹配。</summary>
  69. public static bool EndsWith(this byte[] bytes, params byte[] foot)
  70. {
  71. // 尾部为空,视为匹配。
  72. if (foot == null) return true;
  73. var length = foot.Length;
  74. if (length < 1) return true;
  75. // 样本为空,视为不匹配。
  76. if (bytes == null) return false;
  77. if (bytes.Length < length) return false;
  78. // 对比尾部字节。
  79. var offset = bytes.Length - length;
  80. for (var i = 0; i < length; i++)
  81. {
  82. if (bytes[offset + i] != foot[i]) return false;
  83. }
  84. return true;
  85. }
  86. /// <summary>合并字节数组。</summary>
  87. public static byte[] Merge(IEnumerable<byte[]> array)
  88. {
  89. if (array == null) return Empty;
  90. var total = 0L;
  91. foreach (var bytes in array)
  92. {
  93. if (bytes == null) continue;
  94. total += bytes.LongLength;
  95. }
  96. var result = new byte[total];
  97. var offset = 0L;
  98. if (total > 0)
  99. {
  100. foreach (var bytes in array)
  101. {
  102. if (bytes == null) continue;
  103. var length = bytes.LongLength;
  104. if (length < 1L) continue;
  105. Array.Copy(bytes, 0L, result, offset, length);
  106. offset += length;
  107. }
  108. }
  109. return result;
  110. }
  111. /// <summary>合并字节数组。</summary>
  112. public static byte[] Merge(params byte[][] array) => Merge(array as IEnumerable<byte[]>);
  113. /// <summary>为字节数组增加字节。</summary>
  114. public static byte[] Append(byte[] head, params byte[] bytes) => Merge(head, bytes);
  115. /// <summary>为文本数据添加 BOM 字节,若已存在则忽略。</summary>
  116. public static byte[] AddTextBom(this byte[] bytes)
  117. {
  118. var bom = new byte[] { 0xEF, 0xBB, 0xBF };
  119. if (bytes == null || bytes.LongLength < 1L) return bom;
  120. var hasBom = (bytes.Length >= 3) && (bytes[0] == 0xEF) && (bytes[1] == 0xBB) && (bytes[2] == 0xBF);
  121. return hasBom ? Merge(bytes) : Merge(bom, bytes);
  122. }
  123. /// <summary>去除文本数据的 BOM 字节,若不存在则忽略。</summary>
  124. public static byte[] WipeTextBom(this byte[] bytes)
  125. {
  126. if (bytes == null) return Empty;
  127. var hasBom = (bytes.Length >= 3) && (bytes[0] == 0xEF) && (bytes[1] == 0xBB) && (bytes[2] == 0xBF);
  128. var offset = hasBom ? 3 : 0;
  129. var length = bytes.Length - offset;
  130. var wiped = new byte[length];
  131. if (length > 0) Array.Copy(bytes, offset, wiped, 0, length);
  132. return wiped;
  133. }
  134. /// <summary>生成新的 GUID 数据。</summary>
  135. public static byte[] NewGuid() => Guid.NewGuid().ToByteArray();
  136. #endregion
  137. #region Text
  138. /// <summary>将字节数组转换为十六进制文本。</summary>
  139. public static string ToHex(this byte[] bytes)
  140. {
  141. int length = bytes.Length;
  142. if (length > 0)
  143. {
  144. var sb = new StringBuilder();
  145. for (int i = 0; i < length; i++)
  146. {
  147. sb.Append(Constant.HexCollection[bytes[i] / 16]);
  148. sb.Append(Constant.HexCollection[bytes[i] % 16]);
  149. }
  150. return sb.ToString();
  151. }
  152. return "";
  153. }
  154. /// <summary>将十六进制文本转换为字节数组。</summary>
  155. public static byte[] FromHex(this string hex)
  156. {
  157. if (string.IsNullOrEmpty(hex) || hex.Length < 2) return Empty;
  158. if (hex.Length % 2 != 0) return Empty;
  159. var lower = hex.ToLower().ToCharArray();
  160. var half = lower.Length / 2;
  161. var bytes = new byte[half];
  162. for (var i = 0; i < half; i++)
  163. {
  164. var offset = i * 2;
  165. var h = Constant.HexCollection.IndexOf(lower[offset]);
  166. var l = Constant.HexCollection.IndexOf(lower[offset + 1]);
  167. if (h < 0 || l < 0) return Empty;
  168. bytes[i] = Convert.ToByte((h * 16) + l);
  169. }
  170. return bytes;
  171. }
  172. /// <summary>将字节数组格式化为十六进制字符串,可指定大小写。</summary>
  173. /// <remarks>例:D41D8CD98F00B204E9800998ECF8427E</remarks>
  174. public static string ToX2(this byte[] bytes, bool upper = true)
  175. {
  176. if (bytes == null) return "";
  177. var length = bytes.Length;
  178. if (length < 1) return TextUtility.Empty;
  179. var hex = upper ? UpperHex : LowerHex;
  180. var chars = new char[length * 2];
  181. for (var i = 0; i < length; i++)
  182. {
  183. var b = bytes[i];
  184. var offset = i * 2;
  185. chars[offset] = hex[b / 16];
  186. chars[offset + 1] = hex[b % 16];
  187. }
  188. return new string(chars);
  189. }
  190. /// <summary>将字节数组格式化为十六进制字符串,可指定大小写。</summary>
  191. /// <remarks>例:D41D8CD98F00B204E9800998ECF8427E</remarks>
  192. public static string ToX2(this byte[] bytes, string separator, bool upper = true)
  193. {
  194. if (bytes == null) return "";
  195. var join = separator.NotEmpty();
  196. var length = bytes.Length;
  197. if (length < 1) return TextUtility.Empty;
  198. var sb = new StringBuilder();
  199. var hex = upper ? UpperHex : LowerHex;
  200. for (var i = 0; i < length; i++)
  201. {
  202. var value = bytes[i];
  203. var offset = i * 2;
  204. var a = hex[value / 16];
  205. var b = hex[value % 16];
  206. if (i > 0 && join) sb.Append(separator);
  207. sb.Append(a);
  208. sb.Append(b);
  209. }
  210. return sb.ToString();
  211. }
  212. /// <summary>Byte[] -> Base64</summary>
  213. public static string ToBase64(params byte[] bytes)
  214. {
  215. if (bytes == null || bytes.Length < 1) return Constant.EmptyString;
  216. try { return Convert.ToBase64String(bytes); }
  217. catch { return Constant.EmptyString; }
  218. }
  219. /// <summary>Base64 -> Byte[]</summary>
  220. public static byte[] FromBase64(string base64)
  221. {
  222. if (string.IsNullOrEmpty(base64)) return Empty;
  223. try { return Convert.FromBase64String(base64); }
  224. catch { return Empty; }
  225. }
  226. /// <summary>转换字节数组为文本,默认使用 UTF-8 代码页。</summary>
  227. public static string ToText(byte[] bytes, Encoding encoding = null)
  228. {
  229. if (bytes.Length < 1) return Constant.EmptyString;
  230. try { return (encoding ?? Encoding.UTF8).GetString(bytes); }
  231. catch { return Constant.EmptyString; }
  232. }
  233. /// <summary>转换文本为字节数组,默认使用 UTF-8 代码页。</summary>
  234. public static byte[] FromText(string text, Encoding encoding = null)
  235. {
  236. if (string.IsNullOrEmpty(text)) return Empty;
  237. try { return (encoding ?? Encoding.UTF8).GetBytes(text); }
  238. catch { return Empty; }
  239. }
  240. #endregion
  241. #region 压缩、解压。
  242. /// <summary>对数据进行 GZip 压缩。</summary>
  243. public static byte[] ToGzip(byte[] plain)
  244. {
  245. if (plain == null || plain.Length == 0) return Empty;
  246. byte[] result;
  247. using (var output = new MemoryStream())
  248. {
  249. using (var zip = new GZipStream(output, CompressionMode.Compress, true))
  250. {
  251. zip.Write(plain, 0, plain.Length);
  252. }
  253. result = output.ToArray();
  254. }
  255. return result;
  256. }
  257. /// <summary>对数据进行 GZip 解压。</summary>
  258. public static byte[] FromGzip(byte[] gzip)
  259. {
  260. if (gzip == null || gzip.Length == 0) return Empty;
  261. byte[] result;
  262. using (var input = new MemoryStream(gzip))
  263. {
  264. input.Position = 0;
  265. using (var output = new MemoryStream())
  266. {
  267. using (var zip = new GZipStream(input, CompressionMode.Decompress, true))
  268. {
  269. Read(zip, output, null, 8192);
  270. result = output.ToArray();
  271. }
  272. }
  273. }
  274. return result;
  275. }
  276. /// <summary>压缩字典为 ZIP 文件。</summary>
  277. /// <param name="files">由文件名和文件内容组成的字典。</param>
  278. /// <param name="target">要输出的 ZIP 流。</param>
  279. public static Exception ToZip(Dictionary<string, byte[]> files, Stream target)
  280. {
  281. var zip = null as ZipOutputStream;
  282. try
  283. {
  284. if (files == null) return new ArgumentNullException();
  285. if (target == null) return new ArgumentNullException();
  286. if (!target.CanWrite) return new NotSupportedException();
  287. zip = new ZipOutputStream(target);
  288. zip.SetLevel(1);
  289. foreach (var file in files)
  290. {
  291. var crc = new Crc32();
  292. crc.Reset();
  293. crc.Update(file.Value);
  294. var zipentry = new ZipEntry(file.Key);
  295. zipentry.CompressionMethod = CompressionMethod.Deflated;
  296. //vzipentry.Size = vfile.Value.LongLength;
  297. zipentry.Crc = crc.Value;
  298. zipentry.IsUnicodeText = true;
  299. zip.PutNextEntry(zipentry);
  300. zip.Write(file.Value, 0, file.Value.Length);
  301. zip.CloseEntry();
  302. }
  303. zip.IsStreamOwner = false;
  304. zip.Finish();
  305. zip.Flush();
  306. zip.Close();
  307. return null;
  308. }
  309. catch (Exception ex)
  310. {
  311. RuntimeUtility.Dispose(zip);
  312. return ex;
  313. }
  314. }
  315. /// <summary>压缩到 ZIP 流。</summary>
  316. /// <param name="names">ZIP 内的文件名。</param>
  317. /// <param name="target">要输出的 ZIP 流。</param>
  318. /// <param name="inputGetter">按名称获取文件的输入流。</param>
  319. /// <param name="modifildGetter">按名称获取文件的修改时间。</param>
  320. /// <param name="disposeFiles">释放已写入 ZIP 的输入流。</param>
  321. public static Exception ToZip(IEnumerable<string> names, Stream target, Func<string, Stream> inputGetter, Func<string, DateTime> modifildGetter = null, bool disposeFiles = false)
  322. {
  323. var zip = null as ZipOutputStream;
  324. try
  325. {
  326. if (names == null) return new ArgumentNullException("names");
  327. if (target == null) return new ArgumentNullException("target");
  328. if (!target.CanWrite) return new ArgumentNullException("target");
  329. zip = new ZipOutputStream(target);
  330. zip.SetLevel(1);
  331. foreach (var name in names)
  332. {
  333. if (string.IsNullOrEmpty(name)) continue;
  334. // stream
  335. var capacity = 1024;
  336. var input = inputGetter == null ? null : inputGetter(name);
  337. if (input != null)
  338. {
  339. if (!input.CanSeek || !input.CanRead)
  340. {
  341. if (disposeFiles) RuntimeUtility.Dispose(input);
  342. return new NotSupportedException("获取到的输入流不支持 Seek 或 Read。");
  343. }
  344. }
  345. var crc = new Crc32();
  346. crc.Reset();
  347. if (input != null)
  348. {
  349. input.ResetPosition();
  350. while (true)
  351. {
  352. var count = 0;
  353. var buffer = new byte[capacity];
  354. count = input.Read(buffer, 0, buffer.Length);
  355. if (count == 0) break;
  356. crc.Update(buffer, 0, count);
  357. }
  358. }
  359. var entry = new ZipEntry(name);
  360. entry.CompressionMethod = CompressionMethod.Deflated;
  361. //vzipentry.Size = vfile.Value.LongLength;
  362. entry.Crc = crc.Value;
  363. entry.IsUnicodeText = true;
  364. if (modifildGetter != null) entry.DateTime = modifildGetter(name);
  365. zip.PutNextEntry(entry);
  366. if (input != null)
  367. {
  368. input.ResetPosition();
  369. while (true)
  370. {
  371. var count = 0;
  372. var buffer = new byte[capacity];
  373. count = input.Read(buffer, 0, buffer.Length);
  374. if (count == 0) break;
  375. zip.Write(buffer, 0, count);
  376. }
  377. }
  378. zip.CloseEntry();
  379. if (disposeFiles) RuntimeUtility.Dispose(input);
  380. }
  381. zip.IsStreamOwner = false;
  382. zip.Finish();
  383. zip.Flush();
  384. zip.Close();
  385. return null;
  386. }
  387. catch (Exception ex)
  388. {
  389. RuntimeUtility.Dispose(zip);
  390. return ex;
  391. }
  392. }
  393. /// <summary>压缩字典为 ZIP 包。</summary>
  394. /// <param name="files">由文件名和文件内容组成的字典。</param>
  395. public static byte[] ToZip(Dictionary<string, byte[]> files)
  396. {
  397. if (files == null) return null;
  398. var output = new MemoryStream();
  399. var input = null as Stream;
  400. var ex = ToZip(files.Keys, output, (name) =>
  401. {
  402. RuntimeUtility.Dispose(input);
  403. if (name.IsEmpty()) return null;
  404. var bytes = files[name];
  405. if (bytes == null || bytes.LongLength < 1L) return null;
  406. input = new MemoryStream();
  407. Write(input, bytes);
  408. return input;
  409. }, null, true);
  410. RuntimeUtility.Dispose(input);
  411. var result = output.ToArray();
  412. RuntimeUtility.Dispose(result);
  413. return result;
  414. }
  415. /// <summary>解压 ZIP 文件。</summary>
  416. public static Exception FromZip(Stream input, ZipOnFile onFile, ZipOnDirectory onDirectory = null, bool disposeOutput = false)
  417. {
  418. const int BufferCapacity = 1024;
  419. var zip = null as ZipInputStream;
  420. try
  421. {
  422. if (input == null) return new ArgumentNullException("input");
  423. if (!input.CanRead) return new NotSupportedException();
  424. if (onFile == null) return new ArgumentNullException("extraction");
  425. zip = new ZipInputStream(input);
  426. while (true)
  427. {
  428. var entry = zip.GetNextEntry();
  429. if (entry == null) break;
  430. var name = entry.Name;
  431. var size = entry.Size;
  432. var modified = entry.DateTime;
  433. if (entry.IsFile)
  434. {
  435. var output = null as Stream;
  436. try
  437. {
  438. output = onFile(name, size, modified);
  439. if (output == null) continue;
  440. if (!output.CanWrite)
  441. {
  442. RuntimeUtility.Dispose(output);
  443. continue;
  444. }
  445. var writed = 0L;
  446. while (true)
  447. {
  448. var buffer = new byte[BufferCapacity];
  449. var count = zip.Read(buffer, 0, BufferCapacity);
  450. writed += count;
  451. if (count < 1) break;
  452. output.Write(buffer, 0, count);
  453. }
  454. if (disposeOutput) RuntimeUtility.Dispose(output, true);
  455. }
  456. catch (Exception ex)
  457. {
  458. if (disposeOutput) RuntimeUtility.Dispose(output, true);
  459. RuntimeUtility.Dispose(zip);
  460. return ex;
  461. }
  462. }
  463. if (onDirectory != null && entry.IsDirectory)
  464. {
  465. try
  466. {
  467. onDirectory(name, modified);
  468. }
  469. catch (Exception ex)
  470. {
  471. RuntimeUtility.Dispose(zip);
  472. return ex;
  473. }
  474. }
  475. }
  476. zip.Dispose();
  477. return null;
  478. }
  479. catch (Exception ex)
  480. {
  481. RuntimeUtility.Dispose(zip);
  482. return ex;
  483. }
  484. }
  485. /// <summary>解压 .ZIP 文件为字典。</summary>
  486. public static Dictionary<string, byte[]> FromZip(byte[] zip)
  487. {
  488. var result = new Dictionary<string, byte[]>();
  489. if (zip == null) return result;
  490. if (zip.LongLength < 1) return result;
  491. var packagememory = new System.IO.MemoryStream(zip);
  492. try
  493. {
  494. var zipstream = new ZipInputStream(packagememory);
  495. while (true)
  496. {
  497. var entry = zipstream.GetNextEntry();
  498. if (entry == null) break;
  499. if (entry.IsFile)
  500. {
  501. var cellname = entry.Name;
  502. var celldata = new byte[0];
  503. {
  504. var cellstream = new System.IO.MemoryStream();
  505. while (true)
  506. {
  507. var blockdata = new byte[1024];
  508. var blockread = zipstream.Read(blockdata, 0, 1024);
  509. if (blockread < 1) break;
  510. cellstream.Write(blockdata, 0, blockread);
  511. }
  512. celldata = cellstream.ToArray();
  513. cellstream.Dispose();
  514. }
  515. if (result.ContainsKey(cellname)) result[cellname] = celldata;
  516. else result.Add(cellname, celldata);
  517. }
  518. }
  519. zipstream.Dispose();
  520. }
  521. catch (Exception ex)
  522. {
  523. Debug.WriteLine(ex.ToString());
  524. }
  525. packagememory.Dispose();
  526. return result;
  527. }
  528. #endregion
  529. #region Stream
  530. /// <summary>关闭,并释放流。</summary>
  531. public static void Dispose(Stream stream, bool flush = false, bool close = true)
  532. {
  533. if (stream != null)
  534. {
  535. try { if (flush) stream.Flush(); } catch { }
  536. try { if (close) stream.Close(); } catch { }
  537. try { stream.Dispose(); } catch { }
  538. }
  539. }
  540. /// <summary>关闭,并释放流。</summary>
  541. public static void Dispose(IEnumerable<Stream> streams, bool flush = false, bool close = true)
  542. {
  543. if (streams != null)
  544. {
  545. foreach (var stream in streams) Dispose(stream, flush, close);
  546. }
  547. }
  548. /// <summary>重置流的位置到开始位置。</summary>
  549. public static bool ResetPosition(Stream stream)
  550. {
  551. if (stream == null) return false;
  552. try
  553. {
  554. stream.Position = 0;
  555. if (stream.CanSeek) stream.Seek(0, SeekOrigin.Begin);
  556. return true;
  557. }
  558. catch
  559. {
  560. return false;
  561. }
  562. }
  563. /// <summary>读取源流中的数据,并将数据写入目标流,获取写入的总字节数。</summary>
  564. /// <param name="source">要读取的源流。</param>
  565. /// <param name="destination">要写入的目标流。</param>
  566. /// <param name="progress">已写入的字节数,返回 TRUE 继续读取,返回 FALSE 中断读取。</param>
  567. /// <param name="buffer">缓冲区大小,最小值为 1。</param>
  568. /// <returns>已写入的字节数。</returns>
  569. public static long Read(Stream source, Stream destination, Func<long, bool> progress = null, int buffer = DefaultBuffer)
  570. {
  571. if (source == null || !source.CanRead) return 0;
  572. if (destination == null || !destination.CanWrite) return 0;
  573. var limit = buffer < 1 ? 1 : buffer;
  574. var total = 0L;
  575. var count = 0;
  576. var callback = progress == null ? false : true;
  577. while (true)
  578. {
  579. count = 0;
  580. var temp = new byte[limit];
  581. try
  582. {
  583. count = source.Read(temp, 0, limit);
  584. if (count < 1) break;
  585. }
  586. catch { break; }
  587. try
  588. {
  589. destination.Write(temp, 0, count);
  590. }
  591. catch { break; }
  592. total += count;
  593. if (callback)
  594. {
  595. var @continue = progress(total);
  596. if (!@continue) break;
  597. }
  598. }
  599. return total;
  600. }
  601. /// <summary>读取源流中的数据,并将数据写入目标流,获取写入的总字节数。</summary>
  602. /// <param name="source">要读取的源流。</param>
  603. /// <param name="destination">要写入的目标流。</param>
  604. /// <param name="progress">已写入的字节数,返回 TRUE 继续读取,返回 FALSE 中断读取。</param>
  605. /// <param name="buffer">缓冲区大小,最小值为 1。</param>
  606. /// <returns>已写入的字节数。</returns>
  607. public static long Read(Stream source, Stream destination, Action<long> progress, int buffer = DefaultBuffer)
  608. {
  609. return Read(source, destination, (x) => { progress?.Invoke(x); return true; }, buffer);
  610. }
  611. /// <summary>读取源流中的数据。</summary>
  612. /// <param name="source">源流。</param>
  613. /// <param name="buffer">缓冲区大小,最小值为 1。</param>
  614. /// <param name="dispose">读取结束后释放源流。</param>
  615. public static byte[] Read(Stream source, int buffer = 4096, bool dispose = false)
  616. {
  617. var result = null as byte[];
  618. using (var memory = new MemoryStream())
  619. {
  620. Read(source, memory, null, buffer);
  621. result = memory.ToArray();
  622. }
  623. if (dispose) Dispose(source);
  624. return result;
  625. }
  626. /// <summary>读取源流中的数据。</summary>
  627. /// <param name="source">源流。</param>
  628. /// <param name="dispose">读取结束后释放源流。</param>
  629. public static byte[] Read(Stream source, bool dispose) => Read(source, DefaultBuffer, dispose);
  630. /// <summary>读取源流中的数据,并将数据写入目标流,获取写入的总字节数。</summary>
  631. /// <param name="sources">要读取的源流。</param>
  632. /// <param name="destination">要写入的目标流。</param>
  633. /// <param name="writed">已写入的字节数,返回 TRUE 继续读取,返回 FALSE 中断读取。</param>
  634. /// <param name="buffer">缓冲区大小,最小值为 1。</param>
  635. /// <returns>已写入的字节数。</returns>
  636. public static long Read(IEnumerable<Stream> sources, Stream destination, Func<long, bool> writed = null, int buffer = DefaultBuffer)
  637. {
  638. var total = 0L;
  639. if (sources != null)
  640. {
  641. if (writed == null)
  642. {
  643. foreach (var source in sources) total += Read(source, destination, null, buffer);
  644. }
  645. else
  646. {
  647. foreach (var source in sources)
  648. {
  649. Read(source, destination, (x) =>
  650. {
  651. total += x;
  652. return writed(total);
  653. }, buffer);
  654. }
  655. }
  656. }
  657. return total;
  658. }
  659. /// <summary>读取源流中的数据,并将数据写入目标流,获取写入的总字节数。</summary>
  660. /// <param name="sources">要读取的源流。</param>
  661. /// <param name="destination">要写入的目标流。</param>
  662. /// <param name="writed">已写入的字节数,返回 TRUE 继续读取,返回 FALSE 中断读取。</param>
  663. /// <param name="buffer">缓冲区大小,最小值为 1。</param>
  664. /// <returns>已写入的字节数。</returns>
  665. public static long Read(IEnumerable<Stream> sources, Stream destination, Action<long> writed, int buffer = DefaultBuffer)
  666. {
  667. return Read(sources, destination, (x) => { writed?.Invoke(x); return true; }, buffer);
  668. }
  669. /// <summary>向目标流写入数据,最多可写入 2147483648 字节。</summary>
  670. public static int Write(Stream destination, byte[] bytes, Action<long> writed, int buffer = DefaultBuffer)
  671. {
  672. if (destination == null || !destination.CanWrite) return 0;
  673. if (bytes == null || bytes.Length < 1 || bytes.LongLength > int.MaxValue) return 0;
  674. var limit = buffer < 1 ? 1 : buffer;
  675. var total = 0;
  676. try
  677. {
  678. var length = bytes.Length;
  679. while (total < length)
  680. {
  681. var block = length - total;
  682. if (block > limit) block = limit;
  683. destination.Write(bytes, total, block);
  684. total += block;
  685. writed?.Invoke(total);
  686. }
  687. }
  688. catch (Exception ex)
  689. {
  690. Logger.Internals.Exception(ex, $"{nameof(BytesUtility)}.{nameof(Write)}");
  691. }
  692. return total;
  693. }
  694. /// <summary>向目标流写入数据,最多可写入 2147483647 字节(> 20 GB)。</summary>
  695. public static int Write(Stream destination, params byte[] bytes) => Write(destination, bytes, null);
  696. #endregion
  697. #region PKCS #5
  698. /// <summary>使用密码生成密钥。</summary>
  699. static byte[] PKCS5(byte[] password, byte[] salt = null, int iterations = 1000, int bits = 32)
  700. {
  701. var rfc2898 = new Rfc2898DeriveBytes(password, salt, 1);
  702. return rfc2898.GetBytes(32);
  703. }
  704. #endregion
  705. #region AES
  706. private static void Aes256(byte[] key, byte[] salt, Func<RijndaelManaged, ICryptoTransform> create, Stream input, Stream output)
  707. {
  708. using (var rm = new RijndaelManaged())
  709. {
  710. rm.KeySize = 256;
  711. rm.BlockSize = 128;
  712. rm.Mode = CipherMode.ECB;
  713. rm.Padding = PaddingMode.PKCS7;
  714. var k = new Rfc2898DeriveBytes(SHA256(key), salt, 1);
  715. rm.Key = k.GetBytes(32);
  716. rm.IV = k.GetBytes(16);
  717. using (var ct = create.Invoke(rm))
  718. {
  719. using (var cs = new CryptoStream(output, ct, CryptoStreamMode.Write))
  720. {
  721. Read(input, cs);
  722. cs.Close();
  723. }
  724. }
  725. }
  726. }
  727. /// <summary>执行 AES 加密。</summary>
  728. public static void Aes256Encrypt(Stream input, Stream output, byte[] key) => Aes256(key, key, rm => rm.CreateEncryptor(), input, output);
  729. /// <summary>执行 AES 解密。</summary>
  730. public static void Aes256Decrypt(Stream input, Stream output, byte[] key) => Aes256(key, key, rm => rm.CreateDecryptor(), input, output);
  731. private static RijndaelManaged Aes256Provider(byte[] key)
  732. {
  733. var k = key ?? Empty; // AesFill(key);
  734. var p = new RijndaelManaged();
  735. p.Key = k;
  736. p.Mode = CipherMode.ECB;
  737. p.Padding = PaddingMode.PKCS7;
  738. return p;
  739. }
  740. /// <summary>对数据进行 AES 加密。</summary>
  741. public static byte[] Aes256Encrypt(byte[] bytes, byte[] key = null)
  742. {
  743. if (bytes == null) return Empty;
  744. if (bytes.Length == 0) return Empty;
  745. var rm = Aes256Provider(key);
  746. var result = new byte[0];
  747. var ct = rm.CreateEncryptor();
  748. try
  749. {
  750. result = ct.TransformFinalBlock(bytes, 0, bytes.Length);
  751. }
  752. catch { }
  753. return result;
  754. }
  755. /// <summary>对数据进行 AES 解密。</summary>
  756. public static byte[] Aes256Decrypt(byte[] cipher, byte[] key = null)
  757. {
  758. if (cipher == null) return Empty;
  759. if (cipher.Length == 0) return Empty;
  760. var rm = Aes256Provider(key);
  761. var result = new byte[0];
  762. var ct = rm.CreateDecryptor();
  763. try
  764. {
  765. result = ct.TransformFinalBlock(cipher, 0, cipher.Length);
  766. }
  767. catch { }
  768. ct.Dispose();
  769. return result;
  770. }
  771. private static readonly byte[] AesDefaultIV = new byte[16];
  772. static T UseAes<T>(byte[] key, byte[] iv, CipherMode cipherMode, PaddingMode paddingMode, Func<RijndaelManaged, T> callback)
  773. {
  774. if (key == null) throw new ArgumentNullException(nameof(key));
  775. var keySize = key.Length * 8;
  776. switch (keySize)
  777. {
  778. case 128:
  779. case 192:
  780. case 256:
  781. break;
  782. default:
  783. throw new ArgumentException($"密钥大小【{keySize}】bits 无效。");
  784. }
  785. if (iv == null) iv = AesDefaultIV;
  786. var ivSize = iv.Length * 8;
  787. if (ivSize != 128) throw new ArgumentException($"初始化向量【{ivSize}】bits 无效。");
  788. using (var rijndael = new RijndaelManaged())
  789. {
  790. rijndael.Key = key;
  791. rijndael.IV = iv;
  792. rijndael.Mode = cipherMode;
  793. rijndael.Padding = paddingMode;
  794. return callback.Invoke(rijndael);
  795. }
  796. }
  797. static void UseAes(Stream input, Stream output, byte[] key, byte[] iv, CipherMode cipherMode, PaddingMode paddingMode, Func<RijndaelManaged, ICryptoTransform> create)
  798. {
  799. if (input == null) throw new ArgumentNullException(nameof(input));
  800. if (output == null) throw new ArgumentNullException(nameof(output));
  801. UseAes<object>(key, iv, cipherMode, paddingMode, rijndael =>
  802. {
  803. using (var transformer = create.Invoke(rijndael))
  804. {
  805. using (var stream = new CryptoStream(output, transformer, CryptoStreamMode.Write))
  806. {
  807. Read(input, stream);
  808. stream.Close();
  809. }
  810. }
  811. return null;
  812. });
  813. }
  814. static byte[] UseAes(byte[] input, byte[] key, byte[] iv, CipherMode cipherMode, PaddingMode paddingMode, Func<RijndaelManaged, ICryptoTransform> create)
  815. {
  816. if (input == null) input = new byte[0];
  817. var result = null as byte[];
  818. return UseAes<byte[]>(key, iv, cipherMode, paddingMode, rijndael =>
  819. {
  820. using (var transformer = create.Invoke(rijndael))
  821. {
  822. var result = transformer.TransformFinalBlock(input, 0, input.Length);
  823. return result;
  824. }
  825. });
  826. }
  827. /// <summary>执行 AES 128/192/256 加密。</summary>
  828. /// <param name="plain">明文。</param>
  829. /// <param name="key">密钥。</param>
  830. /// <param name="cipherMode">块密码模式。</param>
  831. /// <param name="paddingMode">填充模式。</param>
  832. /// <returns></returns>
  833. /// <exception cref="ArgumentNullException" />
  834. /// <exception cref="ArgumentException" />
  835. /// <exception cref="CryptographicException" />
  836. public static byte[] AesEncrypt(byte[] plain, byte[] key, CipherMode cipherMode = CipherMode.ECB, PaddingMode paddingMode = PaddingMode.PKCS7)
  837. {
  838. return UseAes(plain, key, null, cipherMode, paddingMode, (rijndael) => rijndael.CreateEncryptor(rijndael.Key, rijndael.IV));
  839. }
  840. /// <summary>执行 AES 128/192/256 加密。</summary>
  841. /// <param name="plain">明文。</param>
  842. /// <param name="key">密钥,长度必须是 128 位(16 字节)、192 位(24 字节)或 256 位(32 字节)。</param>
  843. /// <param name="iv">初始化向量,必须是 128 位(16 字节)。</param>
  844. /// <param name="cipherMode">块密码模式。</param>
  845. /// <param name="paddingMode">填充模式。</param>
  846. /// <returns></returns>
  847. /// <exception cref="ArgumentNullException" />
  848. /// <exception cref="ArgumentException" />
  849. /// <exception cref="CryptographicException" />
  850. public static byte[] AesEncrypt(byte[] plain, byte[] key, byte[] iv, CipherMode cipherMode = CipherMode.ECB, PaddingMode paddingMode = PaddingMode.PKCS7)
  851. {
  852. return UseAes(plain, key, iv, cipherMode, paddingMode, (rijndael) => rijndael.CreateEncryptor(rijndael.Key, rijndael.IV));
  853. }
  854. /// <summary>执行 AES 128/192/256 解密。</summary>
  855. /// <param name="cipher">密文。</param>
  856. /// <param name="key">密钥,长度必须是 128 位(16 字节)、192 位(24 字节)或 256 位(32 字节)。</param>
  857. /// <param name="cipherMode">块密码模式。</param>
  858. /// <param name="paddingMode">填充模式。</param>
  859. /// <returns></returns>
  860. /// <exception cref="ArgumentNullException" />
  861. /// <exception cref="ArgumentException" />
  862. /// <exception cref="CryptographicException" />
  863. public static byte[] AesDecrypt(byte[] cipher, byte[] key, CipherMode cipherMode = CipherMode.ECB, PaddingMode paddingMode = PaddingMode.PKCS7)
  864. {
  865. return UseAes(cipher, key, null, cipherMode, paddingMode, (rijndael) => rijndael.CreateEncryptor(rijndael.Key, rijndael.IV));
  866. }
  867. /// <summary>执行 AES 128/192/256 解密。</summary>
  868. /// <param name="cipher">密文。</param>
  869. /// <param name="key">密钥,长度必须是 128 位(16 字节)、192 位(24 字节)或 256 位(32 字节)。</param>
  870. /// <param name="iv">初始化向量,必须是 128 位(16 字节)。</param>
  871. /// <param name="cipherMode">块密码模式。</param>
  872. /// <param name="paddingMode">填充模式。</param>
  873. /// <returns></returns>
  874. /// <exception cref="ArgumentNullException" />
  875. /// <exception cref="ArgumentException" />
  876. /// <exception cref="CryptographicException" />
  877. public static byte[] AesDecrypt(byte[] cipher, byte[] key, byte[] iv, CipherMode cipherMode = CipherMode.ECB, PaddingMode paddingMode = PaddingMode.PKCS7)
  878. {
  879. return UseAes(cipher, key, iv, cipherMode, paddingMode, (rijndael) => rijndael.CreateEncryptor(rijndael.Key, rijndael.IV));
  880. }
  881. #endregion
  882. #region Hash
  883. private static byte[] ComputeHash<T>(byte[] bytes) where T : HashAlgorithm, new()
  884. {
  885. if (bytes != null)
  886. {
  887. try
  888. {
  889. using (var algorithm = new T())
  890. {
  891. var result = algorithm.ComputeHash(bytes);
  892. algorithm.Clear();
  893. return result;
  894. }
  895. }
  896. catch { }
  897. }
  898. return Empty;
  899. }
  900. private static byte[] ComputeHash<T>(Stream stream, Action<long> progress) where T : HashAlgorithm, new()
  901. {
  902. if (progress == null)
  903. {
  904. using (var algorithm = new T())
  905. {
  906. if (stream == null)
  907. {
  908. var result = algorithm.ComputeHash(Empty);
  909. algorithm.Clear();
  910. return result;
  911. }
  912. else
  913. {
  914. var result = algorithm.ComputeHash(stream);
  915. algorithm.Clear();
  916. return result;
  917. }
  918. }
  919. }
  920. else
  921. {
  922. if (stream == null) return Empty;
  923. // 初始化。
  924. using (var algorithm = new T())
  925. {
  926. algorithm.Initialize();
  927. // 读取。
  928. var count = 0;
  929. var input = new byte[DefaultBuffer];
  930. var output = new byte[DefaultBuffer];
  931. while (true)
  932. {
  933. count = stream.Read(input, 0, DefaultBuffer);
  934. if (count < DefaultBuffer)
  935. {
  936. algorithm.TransformFinalBlock(input, 0, count);
  937. break;
  938. }
  939. else
  940. {
  941. algorithm.TransformBlock(input, 0, count, output, 0);
  942. }
  943. }
  944. var result = algorithm.Hash;
  945. algorithm.Clear();
  946. return result;
  947. }
  948. }
  949. }
  950. /// <summary>获取 MD5 值。</summary>
  951. public static byte[] MD5(this byte[] bytes) => ComputeHash<MD5CryptoServiceProvider>(bytes);
  952. /// <summary>获取 MD5 值。</summary>
  953. public static byte[] MD5(this Stream stream, Action<long> progress = null) => ComputeHash<MD5CryptoServiceProvider>(stream, progress);
  954. /// <summary>获取 SHA1 值。</summary>
  955. public static byte[] SHA1(this byte[] bytes) => ComputeHash<SHA1CryptoServiceProvider>(bytes);
  956. /// <summary>获取 SHA1 值。</summary>
  957. public static byte[] SHA1(this Stream stream, Action<long> progress = null) => ComputeHash<SHA1CryptoServiceProvider>(stream, progress);
  958. /// <summary>获取 SHA256 值。</summary>
  959. public static byte[] SHA256(this byte[] bytes) => ComputeHash<SHA256CryptoServiceProvider>(bytes);
  960. /// <summary>获取 SHA256 值。</summary>
  961. public static byte[] SHA256(this Stream stream, Action<long> progress = null) => ComputeHash<SHA256CryptoServiceProvider>(stream, progress);
  962. /// <summary>获取 SHA512 值。</summary>
  963. public static byte[] SHA512(this byte[] bytes) => ComputeHash<SHA512CryptoServiceProvider>(bytes);
  964. /// <summary>获取 SHA512 值。</summary>
  965. public static byte[] SHA512(this Stream stream, Action<long> progress = null) => ComputeHash<SHA512CryptoServiceProvider>(stream, progress);
  966. /// <summary>计算 CRC16 校验和。</summary>
  967. public static ushort CRC16(this byte[] bytes) => Internals.CRC16.Instance.Compute(bytes);
  968. #endregion
  969. }
  970. }