/
HMACSHA256.cs
345 lines (302 loc) · 14.1 KB
/
HMACSHA256.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Internal.Cryptography;
using System.Diagnostics;
using System.IO;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
namespace System.Security.Cryptography
{
//
// If you change anything in this class, you must make the same change in the other HMAC* classes. This is a pain but given that the
// preexisting contract from the .NET Framework locks all of these into deriving directly from HMAC, it can't be helped.
//
public class HMACSHA256 : HMAC
{
/// <summary>
/// The hash size produced by the HMAC SHA256 algorithm, in bits.
/// </summary>
public const int HashSizeInBits = 256;
/// <summary>
/// The hash size produced by the HMAC SHA256 algorithm, in bytes.
/// </summary>
public const int HashSizeInBytes = HashSizeInBits / 8;
public HMACSHA256()
: this(RandomNumberGenerator.GetBytes(BlockSize))
{
}
public HMACSHA256(byte[] key)
{
ArgumentNullException.ThrowIfNull(key);
this.HashName = HashAlgorithmNames.SHA256;
_hMacCommon = new HMACCommon(HashAlgorithmNames.SHA256, key, BlockSize);
base.Key = _hMacCommon.ActualKey!;
// this not really needed as it'll initialize BlockSizeValue with same value it has which is 64.
// we just want to be explicit in all HMAC extended classes
BlockSizeValue = BlockSize;
HashSizeValue = _hMacCommon.HashSizeInBits;
Debug.Assert(HashSizeValue == HashSizeInBits);
}
public override byte[] Key
{
get
{
return base.Key;
}
set
{
ArgumentNullException.ThrowIfNull(value);
_hMacCommon.ChangeKey(value);
base.Key = _hMacCommon.ActualKey!;
}
}
protected override void HashCore(byte[] rgb, int ib, int cb) =>
_hMacCommon.AppendHashData(rgb, ib, cb);
protected override void HashCore(ReadOnlySpan<byte> source) =>
_hMacCommon.AppendHashData(source);
protected override byte[] HashFinal() =>
_hMacCommon.FinalizeHashAndReset();
protected override bool TryHashFinal(Span<byte> destination, out int bytesWritten) =>
_hMacCommon.TryFinalizeHashAndReset(destination, out bytesWritten);
public override void Initialize() => _hMacCommon.Reset();
/// <summary>
/// Computes the HMAC of data using the SHA256 algorithm.
/// </summary>
/// <param name="key">The HMAC key.</param>
/// <param name="source">The data to HMAC.</param>
/// <returns>The HMAC of the data.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="key" /> or <paramref name="source" /> is <see langword="null" />.
/// </exception>
public static byte[] HashData(byte[] key, byte[] source)
{
ArgumentNullException.ThrowIfNull(key);
ArgumentNullException.ThrowIfNull(source);
return HashData(new ReadOnlySpan<byte>(key), new ReadOnlySpan<byte>(source));
}
/// <summary>
/// Computes the HMAC of data using the SHA256 algorithm.
/// </summary>
/// <param name="key">The HMAC key.</param>
/// <param name="source">The data to HMAC.</param>
/// <returns>The HMAC of the data.</returns>
public static byte[] HashData(ReadOnlySpan<byte> key, ReadOnlySpan<byte> source)
{
byte[] buffer = new byte[HashSizeInBytes];
int written = HashData(key, source, buffer.AsSpan());
Debug.Assert(written == buffer.Length);
return buffer;
}
/// <summary>
/// Computes the HMAC of data using the SHA256 algorithm.
/// </summary>
/// <param name="key">The HMAC key.</param>
/// <param name="source">The data to HMAC.</param>
/// <param name="destination">The buffer to receive the HMAC value.</param>
/// <returns>The total number of bytes written to <paramref name="destination" />.</returns>
/// <exception cref="ArgumentException">
/// The buffer in <paramref name="destination"/> is too small to hold the calculated hash
/// size. The SHA256 algorithm always produces a 256-bit HMAC, or 32 bytes.
/// </exception>
public static int HashData(ReadOnlySpan<byte> key, ReadOnlySpan<byte> source, Span<byte> destination)
{
if (!TryHashData(key, source, destination, out int bytesWritten))
{
throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination));
}
return bytesWritten;
}
/// <summary>
/// Attempts to compute the HMAC of data using the SHA256 algorithm.
/// </summary>
/// <param name="key">The HMAC key.</param>
/// <param name="source">The data to HMAC.</param>
/// <param name="destination">The buffer to receive the HMAC value.</param>
/// <param name="bytesWritten">
/// When this method returns, the total number of bytes written into <paramref name="destination"/>.
/// </param>
/// <returns>
/// <see langword="false"/> if <paramref name="destination"/> is too small to hold the
/// calculated hash, <see langword="true"/> otherwise.
/// </returns>
public static bool TryHashData(ReadOnlySpan<byte> key, ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten)
{
if (destination.Length < HashSizeInBytes)
{
bytesWritten = 0;
return false;
}
bytesWritten = HashProviderDispenser.OneShotHashProvider.MacData(HashAlgorithmNames.SHA256, key, source, destination);
Debug.Assert(bytesWritten == HashSizeInBytes);
return true;
}
/// <summary>
/// Computes the HMAC of a stream using the SHA256 algorithm.
/// </summary>
/// <param name="key">The HMAC key.</param>
/// <param name="source">The stream to HMAC.</param>
/// <param name="destination">The buffer to receive the HMAC value.</param>
/// <returns>The total number of bytes written to <paramref name="destination" />.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentException">
/// <p>
/// The buffer in <paramref name="destination"/> is too small to hold the calculated HMAC
/// size. The SHA256 algorithm always produces a 256-bit HMAC, or 32 bytes.
/// </p>
/// <p>-or-</p>
/// <p>
/// <paramref name="source" /> does not support reading.
/// </p>
/// </exception>
public static int HashData(ReadOnlySpan<byte> key, Stream source, Span<byte> destination)
{
ArgumentNullException.ThrowIfNull(source);
if (destination.Length < HashSizeInBytes)
throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination));
if (!source.CanRead)
throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source));
return LiteHashProvider.HmacStream(HashAlgorithmNames.SHA256, HashSizeInBytes, key, source, destination);
}
/// <summary>
/// Computes the HMAC of a stream using the SHA256 algorithm.
/// </summary>
/// <param name="key">The HMAC key.</param>
/// <param name="source">The stream to HMAC.</param>
/// <returns>The HMAC of the data.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="source" /> does not support reading.
/// </exception>
public static byte[] HashData(ReadOnlySpan<byte> key, Stream source)
{
ArgumentNullException.ThrowIfNull(source);
if (!source.CanRead)
throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source));
return LiteHashProvider.HmacStream(HashAlgorithmNames.SHA256, HashSizeInBytes, key, source);
}
/// <summary>
/// Computes the HMAC of a stream using the SHA256 algorithm.
/// </summary>
/// <param name="key">The HMAC key.</param>
/// <param name="source">The stream to HMAC.</param>
/// <returns>The HMAC of the data.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="key" /> or <paramref name="source" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="source" /> does not support reading.
/// </exception>
public static byte[] HashData(byte[] key, Stream source)
{
ArgumentNullException.ThrowIfNull(key);
return HashData(new ReadOnlySpan<byte>(key), source);
}
/// <summary>
/// Asynchronously computes the HMAC of a stream using the SHA256 algorithm.
/// </summary>
/// <param name="key">The HMAC key.</param>
/// <param name="source">The stream to HMAC.</param>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests.
/// The default value is <see cref="System.Threading.CancellationToken.None" />.
/// </param>
/// <returns>The HMAC of the data.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="source" /> does not support reading.
/// </exception>
public static ValueTask<byte[]> HashDataAsync(ReadOnlyMemory<byte> key, Stream source, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(source);
if (!source.CanRead)
throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source));
return LiteHashProvider.HmacStreamAsync(HashAlgorithmNames.SHA256, HashSizeInBytes, key.Span, source, cancellationToken);
}
/// <summary>
/// Asynchronously computes the HMAC of a stream using the SHA256 algorithm.
/// </summary>
/// <param name="key">The HMAC key.</param>
/// <param name="source">The stream to HMAC.</param>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests.
/// The default value is <see cref="System.Threading.CancellationToken.None" />.
/// </param>
/// <returns>The HMAC of the data.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="key" /> or <paramref name="source" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="source" /> does not support reading.
/// </exception>
public static ValueTask<byte[]> HashDataAsync(byte[] key, Stream source, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(key);
return HashDataAsync(new ReadOnlyMemory<byte>(key), source, cancellationToken);
}
/// <summary>
/// Asynchronously computes the HMAC of a stream using the SHA256 algorithm.
/// </summary>
/// <param name="key">The HMAC key.</param>
/// <param name="source">The stream to HMAC.</param>
/// <param name="destination">The buffer to receive the HMAC value.</param>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests.
/// The default value is <see cref="System.Threading.CancellationToken.None" />.
/// </param>
/// <returns>The total number of bytes written to <paramref name="destination" />.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentException">
/// <p>
/// The buffer in <paramref name="destination"/> is too small to hold the calculated hash
/// size. The SHA256 algorithm always produces a 256-bit hash, or 32 bytes.
/// </p>
/// <p>-or-</p>
/// <p>
/// <paramref name="source" /> does not support reading.
/// </p>
/// </exception>
public static ValueTask<int> HashDataAsync(
ReadOnlyMemory<byte> key,
Stream source,
Memory<byte> destination,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(source);
if (destination.Length < HashSizeInBytes)
throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination));
if (!source.CanRead)
throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source));
return LiteHashProvider.HmacStreamAsync(
HashAlgorithmNames.SHA256,
HashSizeInBytes,
key.Span,
source,
destination,
cancellationToken);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
HMACCommon hMacCommon = _hMacCommon;
if (hMacCommon != null)
{
_hMacCommon = null!;
hMacCommon.Dispose(disposing);
}
}
base.Dispose(disposing);
}
private HMACCommon _hMacCommon;
private const int BlockSize = 64;
}
}