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.

1124 lines
43 KiB

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