/
NonCryptographicHashAlgorithm.cs
350 lines (314 loc) · 13.5 KB
/
NonCryptographicHashAlgorithm.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Hashing
{
/// <summary>
/// Represents a non-cryptographic hash algorithm.
/// </summary>
public abstract class NonCryptographicHashAlgorithm
{
/// <summary>
/// Gets the number of bytes produced from this hash algorithm.
/// </summary>
/// <value>The number of bytes produced from this hash algorithm.</value>
public int HashLengthInBytes { get; }
/// <summary>
/// Called from constructors in derived classes to initialize the
/// <see cref="NonCryptographicHashAlgorithm"/> class.
/// </summary>
/// <param name="hashLengthInBytes">
/// The number of bytes produced from this hash algorithm.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="hashLengthInBytes"/> is less than 1.
/// </exception>
protected NonCryptographicHashAlgorithm(int hashLengthInBytes)
{
if (hashLengthInBytes < 1)
throw new ArgumentOutOfRangeException(nameof(hashLengthInBytes));
HashLengthInBytes = hashLengthInBytes;
}
/// <summary>
/// When overridden in a derived class,
/// appends the contents of <paramref name="source"/> to the data already
/// processed for the current hash computation.
/// </summary>
/// <param name="source">The data to process.</param>
public abstract void Append(ReadOnlySpan<byte> source);
/// <summary>
/// When overridden in a derived class,
/// resets the hash computation to the initial state.
/// </summary>
public abstract void Reset();
/// <summary>
/// When overridden in a derived class,
/// writes the computed hash value to <paramref name="destination"/>
/// without modifying accumulated state.
/// </summary>
/// <param name="destination">The buffer that receives the computed hash value.</param>
/// <remarks>
/// <para>
/// Implementations of this method must write exactly
/// <see cref="HashLengthInBytes"/> bytes to <paramref name="destination"/>.
/// Do not assume that the buffer was zero-initialized.
/// </para>
/// <para>
/// The <see cref="NonCryptographicHashAlgorithm"/> class validates the
/// size of the buffer before calling this method, and slices the span
/// down to be exactly <see cref="HashLengthInBytes"/> in length.
/// </para>
/// </remarks>
protected abstract void GetCurrentHashCore(Span<byte> destination);
/// <summary>
/// Appends the contents of <paramref name="source"/> to the data already
/// processed for the current hash computation.
/// </summary>
/// <param name="source">The data to process.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> is <see langword="null"/>.
/// </exception>
public void Append(byte[] source)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
Append(new ReadOnlySpan<byte>(source));
}
/// <summary>
/// Appends the contents of <paramref name="stream"/> to the data already
/// processed for the current hash computation.
/// </summary>
/// <param name="stream">The data to process.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="stream"/> is <see langword="null"/>.
/// </exception>
/// <seealso cref="AppendAsync(Stream, CancellationToken)"/>
public void Append(Stream stream)
{
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
byte[] buffer = ArrayPool<byte>.Shared.Rent(4096);
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read == 0)
{
break;
}
Append(new ReadOnlySpan<byte>(buffer, 0, read));
}
ArrayPool<byte>.Shared.Return(buffer);
}
/// <summary>
/// Asychronously reads the contents of <paramref name="stream"/>
/// and appends them to the data already
/// processed for the current hash computation.
/// </summary>
/// <param name="stream">The data to process.</param>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests.
/// The default value is <see cref="CancellationToken.None"/>.
/// </param>
/// <returns>
/// A task that represents the asynchronous append operation.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="stream"/> is <see langword="null"/>.
/// </exception>
public Task AppendAsync(Stream stream, CancellationToken cancellationToken = default)
{
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
return AppendAsyncCore(stream, cancellationToken);
}
private async Task AppendAsyncCore(Stream stream, CancellationToken cancellationToken)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(4096);
while (true)
{
#if NETCOREAPP
int read = await stream.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false);
#else
int read = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
#endif
if (read == 0)
{
break;
}
Append(new ReadOnlySpan<byte>(buffer, 0, read));
}
ArrayPool<byte>.Shared.Return(buffer);
}
/// <summary>
/// Gets the current computed hash value without modifying accumulated state.
/// </summary>
/// <returns>
/// The hash value for the data already provided.
/// </returns>
public byte[] GetCurrentHash()
{
byte[] ret = new byte[HashLengthInBytes];
GetCurrentHashCore(ret);
return ret;
}
/// <summary>
/// Attempts to write the computed hash value to <paramref name="destination"/>
/// without modifying accumulated state.
/// </summary>
/// <param name="destination">The buffer that receives the computed hash value.</param>
/// <param name="bytesWritten">
/// On success, receives the number of bytes written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="destination"/> is long enough to receive
/// the computed hash value; otherwise, <see langword="false"/>.
/// </returns>
public bool TryGetCurrentHash(Span<byte> destination, out int bytesWritten)
{
if (destination.Length < HashLengthInBytes)
{
bytesWritten = 0;
return false;
}
GetCurrentHashCore(destination.Slice(0, HashLengthInBytes));
bytesWritten = HashLengthInBytes;
return true;
}
/// <summary>
/// Writes the computed hash value to <paramref name="destination"/>
/// without modifying accumulated state.
/// </summary>
/// <param name="destination">The buffer that receives the computed hash value.</param>
/// <returns>
/// The number of bytes written to <paramref name="destination"/>,
/// which is always <see cref="HashLengthInBytes"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="destination"/> is shorter than <see cref="HashLengthInBytes"/>.
/// </exception>
public int GetCurrentHash(Span<byte> destination)
{
if (destination.Length < HashLengthInBytes)
{
ThrowDestinationTooShort();
}
GetCurrentHashCore(destination.Slice(0, HashLengthInBytes));
return HashLengthInBytes;
}
/// <summary>
/// Gets the current computed hash value and clears the accumulated state.
/// </summary>
/// <returns>
/// The hash value for the data already provided.
/// </returns>
public byte[] GetHashAndReset()
{
byte[] ret = new byte[HashLengthInBytes];
GetHashAndResetCore(ret);
return ret;
}
/// <summary>
/// Attempts to write the computed hash value to <paramref name="destination"/>.
/// If successful, clears the accumulated state.
/// </summary>
/// <param name="destination">The buffer that receives the computed hash value.</param>
/// <param name="bytesWritten">
/// On success, receives the number of bytes written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <see langword="true"/> and clears the accumulated state
/// if <paramref name="destination"/> is long enough to receive
/// the computed hash value; otherwise, <see langword="false"/>.
/// </returns>
public bool TryGetHashAndReset(Span<byte> destination, out int bytesWritten)
{
if (destination.Length < HashLengthInBytes)
{
bytesWritten = 0;
return false;
}
GetHashAndResetCore(destination.Slice(0, HashLengthInBytes));
bytesWritten = HashLengthInBytes;
return true;
}
/// <summary>
/// Writes the computed hash value to <paramref name="destination"/>
/// then clears the accumulated state.
/// </summary>
/// <param name="destination">The buffer that receives the computed hash value.</param>
/// <returns>
/// The number of bytes written to <paramref name="destination"/>,
/// which is always <see cref="HashLengthInBytes"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="destination"/> is shorter than <see cref="HashLengthInBytes"/>.
/// </exception>
public int GetHashAndReset(Span<byte> destination)
{
if (destination.Length < HashLengthInBytes)
{
ThrowDestinationTooShort();
}
GetHashAndResetCore(destination.Slice(0, HashLengthInBytes));
return HashLengthInBytes;
}
/// <summary>
/// Writes the computed hash value to <paramref name="destination"/>
/// then clears the accumulated state.
/// </summary>
/// <param name="destination">The buffer that receives the computed hash value.</param>
/// <remarks>
/// <para>
/// Implementations of this method must write exactly
/// <see cref="HashLengthInBytes"/> bytes to <paramref name="destination"/>.
/// Do not assume that the buffer was zero-initialized.
/// </para>
/// <para>
/// The <see cref="NonCryptographicHashAlgorithm"/> class validates the
/// size of the buffer before calling this method, and slices the span
/// down to be exactly <see cref="HashLengthInBytes"/> in length.
/// </para>
/// <para>
/// The default implementation of this method calls
/// <see cref="GetCurrentHashCore"/> followed by <see cref="Reset"/>.
/// Overrides of this method do not need to call either of those methods,
/// but must ensure that the caller cannot observe a difference in behavior.
/// </para>
/// </remarks>
protected virtual void GetHashAndResetCore(Span<byte> destination)
{
Debug.Assert(destination.Length == HashLengthInBytes);
GetCurrentHashCore(destination);
Reset();
}
/// <summary>
/// This method is not supported and should not be called.
/// Call <see cref="GetCurrentHash()"/> or <see cref="GetHashAndReset()"/>
/// instead.
/// </summary>
/// <returns>This method will always throw a <see cref="NotSupportedException"/>.</returns>
/// <exception cref="NotSupportedException">In all cases.</exception>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use GetCurrentHash() to retrieve the computed hash code.", true)]
#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member
public override int GetHashCode()
#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member
{
throw new NotSupportedException(SR.NotSupported_GetHashCode);
}
[DoesNotReturn]
private protected static void ThrowDestinationTooShort() =>
throw new ArgumentException(SR.Argument_DestinationTooShort, "destination");
}
}