|
31 | 31 | using System.IO; |
32 | 32 | using System.Globalization; |
33 | 33 | using System.ComponentModel; |
34 | | -using System.Security.Cryptography; |
| 34 | +using System.Threading; |
| 35 | +using System.Threading.Tasks; |
35 | 36 | using System.Text.Json; |
36 | 37 | using System.Text.Json.Serialization; |
| 38 | +using System.Security.Cryptography; |
37 | 39 |
|
38 | 40 | namespace Zongsoft.Common; |
39 | 41 |
|
@@ -122,6 +124,34 @@ public static Checksum Compute(string name, Stream data) |
122 | 124 | }; |
123 | 125 | } |
124 | 126 |
|
| 127 | + /// <summary>使用指定哈希算法计算指定数据的校验码。</summary> |
| 128 | + /// <param name="name">指定的哈希算法名称。</param> |
| 129 | + /// <param name="data">指定的待计算的数据。</param> |
| 130 | + /// <param name="cancellation">异步操作的取消标记。</param> |
| 131 | + /// <returns>返回的校验码。</returns> |
| 132 | + /// <exception cref="ArgumentNullException">指定的 <paramref name="data"/> 参数值为空(<c>null</c>)。</exception> |
| 133 | + /// <exception cref="InvalidOperationException">指定的 <paramref name="name"/> 参数值不是一个有效的哈希算法名。</exception> |
| 134 | + public static async ValueTask<Checksum> ComputeAsync(string name, Stream data, CancellationToken cancellation = default) |
| 135 | + { |
| 136 | + ArgumentNullException.ThrowIfNull(data); |
| 137 | + |
| 138 | + if(string.IsNullOrEmpty(name)) |
| 139 | + return new(HashAlgorithmName.SHA1.Name, await SHA1.HashDataAsync(data, cancellation)); |
| 140 | + |
| 141 | + return name.ToUpperInvariant() switch |
| 142 | + { |
| 143 | + "MD5" => new(HashAlgorithmName.MD5.Name, await MD5.HashDataAsync(data, cancellation)), |
| 144 | + "SHA1" => new(HashAlgorithmName.SHA1.Name, await SHA1.HashDataAsync(data, cancellation)), |
| 145 | + "SHA256" => new(HashAlgorithmName.SHA256.Name, await SHA256.HashDataAsync(data, cancellation)), |
| 146 | + "SHA384" => new(HashAlgorithmName.SHA384.Name, await SHA384.HashDataAsync(data, cancellation)), |
| 147 | + "SHA512" => new(HashAlgorithmName.SHA512.Name, await SHA512.HashDataAsync(data, cancellation)), |
| 148 | + "SHA3-256" => new(HashAlgorithmName.SHA3_256.Name, await SHA3_256.HashDataAsync(data, cancellation)), |
| 149 | + "SHA3-384" => new(HashAlgorithmName.SHA3_384.Name, await SHA3_384.HashDataAsync(data, cancellation)), |
| 150 | + "SHA3-512" => new(HashAlgorithmName.SHA3_512.Name, await SHA3_512.HashDataAsync(data, cancellation)), |
| 151 | + _ => throw new InvalidOperationException($"The specified '{name}' is an invalid hash algorithm."), |
| 152 | + }; |
| 153 | + } |
| 154 | + |
125 | 155 | public static Checksum Parse(string text, IFormatProvider provider = null) => string.IsNullOrEmpty(text) ? default : |
126 | 156 | TryParse(text, out var result) ? result : throw new InvalidOperationException($"Invalid checksum text format."); |
127 | 157 |
|
|
0 commit comments