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.

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