-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
DSACng.ImportExport.cs
453 lines (382 loc) · 22.5 KB
/
DSACng.ImportExport.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using Internal.Cryptography;
using System.Diagnostics;
using static Interop.BCrypt;
using static Interop.NCrypt;
using KeyBlobMagicNumber = Interop.BCrypt.KeyBlobMagicNumber;
namespace System.Security.Cryptography
{
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
internal static partial class DSAImplementation
{
#endif
public sealed partial class DSACng : DSA
{
// For keysizes up to and including 1024 bits, CNG's blob format is BCRYPT_DSA_KEY_BLOB.
// For keysizes exceeding 1024 bits, CNG's blob format is BCRYPT_DSA_KEY_BLOB_V2.
private const int MaxV1KeySize = 1024;
private const int Sha1HashOutputSize = 20;
private const int Sha256HashOutputSize = 32;
private const int Sha512HashOutputSize = 64;
public override void ImportParameters(DSAParameters parameters)
{
if (parameters.P == null || parameters.Q == null || parameters.G == null || parameters.Y == null)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MissingFields);
// J is not required and is not even used on CNG blobs. It should however be less than P (J == (P-1) / Q). This validation check
// is just to maintain parity with DSACryptoServiceProvider, which also performs this check.
if (parameters.J != null && parameters.J.Length >= parameters.P.Length)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPJ);
bool hasPrivateKey = parameters.X != null;
int keySizeInBytes = parameters.P.Length;
int keySizeInBits = keySizeInBytes * 8;
if (parameters.G.Length != keySizeInBytes || parameters.Y.Length != keySizeInBytes)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPGY);
if (hasPrivateKey && parameters.X!.Length != parameters.Q.Length)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedQX);
byte[] blob;
if (keySizeInBits <= MaxV1KeySize)
{
GenerateV1DsaBlob(out blob, parameters, keySizeInBytes, hasPrivateKey);
}
else
{
GenerateV2DsaBlob(out blob, parameters, keySizeInBytes, hasPrivateKey);
}
ImportKeyBlob(blob, hasPrivateKey);
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead);
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead);
}
public override byte[] ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters)
{
if (pbeParameters == null)
throw new ArgumentNullException(nameof(pbeParameters));
return CngPkcs8.ExportEncryptedPkcs8PrivateKey(
this,
passwordBytes,
pbeParameters);
}
public override byte[] ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters)
{
if (pbeParameters == null)
{
throw new ArgumentNullException(nameof(pbeParameters));
}
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,
ReadOnlySpan<byte>.Empty);
if (CngPkcs8.IsPlatformScheme(pbeParameters))
{
return ExportEncryptedPkcs8(password, pbeParameters.IterationCount);
}
return CngPkcs8.ExportEncryptedPkcs8PrivateKey(
this,
password,
pbeParameters);
}
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
if (pbeParameters == null)
throw new ArgumentNullException(nameof(pbeParameters));
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
ReadOnlySpan<char>.Empty,
passwordBytes);
return CngPkcs8.TryExportEncryptedPkcs8PrivateKey(
this,
passwordBytes,
pbeParameters,
destination,
out bytesWritten);
}
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
if (pbeParameters == null)
throw new ArgumentNullException(nameof(pbeParameters));
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,
ReadOnlySpan<byte>.Empty);
if (CngPkcs8.IsPlatformScheme(pbeParameters))
{
return TryExportEncryptedPkcs8(
password,
pbeParameters.IterationCount,
destination,
out bytesWritten);
}
return CngPkcs8.TryExportEncryptedPkcs8PrivateKey(
this,
password,
pbeParameters,
destination,
out bytesWritten);
}
private static void GenerateV1DsaBlob(out byte[] blob, DSAParameters parameters, int cbKey, bool includePrivate)
{
// We need to build a key blob structured as follows:
//
// BCRYPT_DSA_KEY_BLOB header
// byte[cbKey] P
// byte[cbKey] G
// byte[cbKey] Y
// -- Private only --
// byte[Sha1HashOutputSize] X
unsafe
{
int blobSize =
sizeof(BCRYPT_DSA_KEY_BLOB) +
cbKey +
cbKey +
cbKey;
if (includePrivate)
{
blobSize += Sha1HashOutputSize;
}
blob = new byte[blobSize];
fixed (byte* pDsaBlob = &blob[0])
{
// Build the header
BCRYPT_DSA_KEY_BLOB* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB*)pDsaBlob;
pBcryptBlob->Magic = includePrivate ? KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC : KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC;
pBcryptBlob->cbKey = cbKey;
int offset = sizeof(KeyBlobMagicNumber) + sizeof(int); // skip Magic and cbKey
if (parameters.Seed != null)
{
// The Seed length is hardcoded into BCRYPT_DSA_KEY_BLOB, so check it now we can give a nicer error message.
if (parameters.Seed.Length != Sha1HashOutputSize)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_SeedRestriction_ShortKey);
Interop.BCrypt.EmitBigEndian(blob, ref offset, parameters.Counter);
Interop.BCrypt.Emit(blob, ref offset, parameters.Seed);
}
else
{
// If Seed is not present, back fill both counter and seed with 0xff. Do not use parameters.Counter as CNG is more strict than CAPI and will reject
// anything other than 0xffffffff. That could complicate efforts to switch usage of DSACryptoServiceProvider to DSACng.
Interop.BCrypt.EmitByte(blob, ref offset, 0xff, Sha1HashOutputSize + sizeof(int));
}
// The Q length is hardcoded into BCRYPT_DSA_KEY_BLOB, so check it now we can give a nicer error message.
if (parameters.Q!.Length != Sha1HashOutputSize)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_QRestriction_ShortKey);
Interop.BCrypt.Emit(blob, ref offset, parameters.Q);
Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB)}");
Interop.BCrypt.Emit(blob, ref offset, parameters.P!);
Interop.BCrypt.Emit(blob, ref offset, parameters.G!);
Interop.BCrypt.Emit(blob, ref offset, parameters.Y!);
if (includePrivate)
{
Interop.BCrypt.Emit(blob, ref offset, parameters.X!);
}
Debug.Assert(offset == blobSize, $"Expected offset = blobSize, got {offset} != {blobSize}");
}
}
}
private static void GenerateV2DsaBlob(out byte[] blob, DSAParameters parameters, int cbKey, bool includePrivateParameters)
{
// We need to build a key blob structured as follows:
// BCRYPT_DSA_KEY_BLOB_V2 header
// byte[cbSeedLength] Seed
// byte[cbGroupSize] Q
// byte[cbKey] P
// byte[cbKey] G
// byte[cbKey] Y
// -- Private only --
// byte[cbGroupSize] X
unsafe
{
int blobSize =
sizeof(BCRYPT_DSA_KEY_BLOB_V2) +
(parameters.Seed == null ? parameters.Q!.Length : parameters.Seed.Length) + // Use Q size if Seed is not present
parameters.Q!.Length +
parameters.P!.Length +
parameters.G!.Length +
parameters.Y!.Length +
(includePrivateParameters ? parameters.X!.Length : 0);
blob = new byte[blobSize];
fixed (byte* pDsaBlob = &blob[0])
{
// Build the header
BCRYPT_DSA_KEY_BLOB_V2* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB_V2*)pDsaBlob;
pBcryptBlob->Magic = includePrivateParameters ? KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2 : KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2;
pBcryptBlob->cbKey = cbKey;
// For some reason, Windows bakes the hash algorithm into the key itself. Furthermore, it demands that the Q length match the
// length of the named hash algorithm's output - otherwise, the Import fails. So we have to give it the hash algorithm that matches
// the Q length - and if there is no matching hash algorithm, we throw up our hands and throw a PlatformNotSupported.
//
// Note that this has no bearing on the hash algorithm you pass to SignData(). The class library (not Windows) hashes that according
// to the hash algorithm passed to SignData() and presents the hash result to NCryptSignHash(), truncating the hash to the Q length
// if necessary (and as demanded by the NIST spec.) Windows will be no wiser and we'll get the result we want.
pBcryptBlob->hashAlgorithm = parameters.Q.Length switch
{
Sha1HashOutputSize => HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA1,
Sha256HashOutputSize => HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA256,
Sha512HashOutputSize => HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA512,
_ => throw new PlatformNotSupportedException(SR.Cryptography_InvalidDsaParameters_QRestriction_LargeKey),
};
pBcryptBlob->standardVersion = DSAFIPSVERSION_ENUM.DSA_FIPS186_3;
int offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2) - 4; //skip to Count[4]
if (parameters.Seed != null)
{
Interop.BCrypt.EmitBigEndian(blob, ref offset, parameters.Counter);
Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB_V2), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB_V2)}");
pBcryptBlob->cbSeedLength = parameters.Seed.Length;
pBcryptBlob->cbGroupSize = parameters.Q.Length;
Interop.BCrypt.Emit(blob, ref offset, parameters.Seed);
}
else
{
// If Seed is not present, back fill both counter and seed with 0xff. Do not use parameters.Counter as CNG is more strict than CAPI and will reject
// anything other than 0xffffffff. That could complicate efforts to switch usage of DSACryptoServiceProvider to DSACng.
Interop.BCrypt.EmitByte(blob, ref offset, 0xff, sizeof(int));
Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB_V2), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB_V2)}");
int defaultSeedLength = parameters.Q.Length;
pBcryptBlob->cbSeedLength = defaultSeedLength;
pBcryptBlob->cbGroupSize = parameters.Q.Length;
Interop.BCrypt.EmitByte(blob, ref offset, 0xff, defaultSeedLength);
}
Interop.BCrypt.Emit(blob, ref offset, parameters.Q);
Interop.BCrypt.Emit(blob, ref offset, parameters.P);
Interop.BCrypt.Emit(blob, ref offset, parameters.G);
Interop.BCrypt.Emit(blob, ref offset, parameters.Y);
if (includePrivateParameters)
{
Interop.BCrypt.Emit(blob, ref offset, parameters.X!);
}
Debug.Assert(offset == blobSize, $"Expected offset = blobSize, got {offset} != {blobSize}");
}
}
}
public override DSAParameters ExportParameters(bool includePrivateParameters)
{
byte[] dsaBlob = ExportKeyBlob(includePrivateParameters);
KeyBlobMagicNumber magic = (KeyBlobMagicNumber)BitConverter.ToInt32(dsaBlob, 0);
// Check the magic value in the key blob header. If the blob does not have the required magic,
// then throw a CryptographicException.
CheckMagicValueOfKey(magic, includePrivateParameters);
unsafe
{
DSAParameters dsaParams = default;
fixed (byte* pDsaBlob = dsaBlob)
{
int offset;
if (magic == KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC || magic == KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC)
{
if (dsaBlob.Length < sizeof(BCRYPT_DSA_KEY_BLOB))
throw ErrorCode.E_FAIL.ToCryptographicException();
BCRYPT_DSA_KEY_BLOB* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB*)pDsaBlob;
// We now have a buffer laid out as follows:
// BCRYPT_DSA_KEY_BLOB header
// byte[cbKey] P
// byte[cbKey] G
// byte[cbKey] Y
// -- Private only --
// byte[Sha1HashOutputSize] X
offset = sizeof(KeyBlobMagicNumber) + sizeof(int); // skip Magic and cbKey
// Read out a (V1) BCRYPT_DSA_KEY_BLOB structure.
dsaParams.Counter = FromBigEndian(Interop.BCrypt.Consume(dsaBlob, ref offset, 4));
dsaParams.Seed = Interop.BCrypt.Consume(dsaBlob, ref offset, Sha1HashOutputSize);
dsaParams.Q = Interop.BCrypt.Consume(dsaBlob, ref offset, Sha1HashOutputSize);
Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB)}");
dsaParams.P = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey);
dsaParams.G = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey);
dsaParams.Y = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey);
if (includePrivateParameters)
{
dsaParams.X = Interop.BCrypt.Consume(dsaBlob, ref offset, Sha1HashOutputSize);
}
}
else
{
Debug.Assert(magic == KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2 || magic == KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2);
if (dsaBlob.Length < sizeof(BCRYPT_DSA_KEY_BLOB_V2))
throw ErrorCode.E_FAIL.ToCryptographicException();
BCRYPT_DSA_KEY_BLOB_V2* pBcryptBlob = (BCRYPT_DSA_KEY_BLOB_V2*)pDsaBlob;
// We now have a buffer laid out as follows:
// BCRYPT_DSA_KEY_BLOB_V2 header
// byte[cbSeedLength] Seed
// byte[cbGroupSize] Q
// byte[cbKey] P
// byte[cbKey] G
// byte[cbKey] Y
// -- Private only --
// byte[cbGroupSize] X
offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2) - 4; //skip to Count[4]
// Read out a BCRYPT_DSA_KEY_BLOB_V2 structure.
dsaParams.Counter = FromBigEndian(Interop.BCrypt.Consume(dsaBlob, ref offset, 4));
Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB_V2), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB_V2), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB_V2)}");
dsaParams.Seed = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbSeedLength);
dsaParams.Q = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbGroupSize);
dsaParams.P = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey);
dsaParams.G = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey);
dsaParams.Y = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbKey);
if (includePrivateParameters)
{
dsaParams.X = Interop.BCrypt.Consume(dsaBlob, ref offset, pBcryptBlob->cbGroupSize);
}
}
// If no counter/seed information is present, normalize Counter and Seed to 0/null to maintain parity with the CAPI version of DSA.
if (dsaParams.Counter == -1)
{
dsaParams.Counter = 0;
dsaParams.Seed = null;
}
Debug.Assert(offset == dsaBlob.Length, $"Expected offset = dsaBlob.Length, got {offset} != {dsaBlob.Length}");
return dsaParams;
}
}
}
private static int FromBigEndian(byte[] b)
{
return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
}
/// <summary>
/// This function checks the magic value in the key blob header
/// </summary>
/// <param name="includePrivateParameters">Private blob if true else public key blob</param>
private static void CheckMagicValueOfKey(KeyBlobMagicNumber magic, bool includePrivateParameters)
{
if (includePrivateParameters)
{
if (magic != KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC && magic != KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2)
throw new CryptographicException(SR.Cryptography_NotValidPrivateKey);
}
else
{
if (magic != KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC && magic != KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2)
throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey);
}
}
}
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
}
#endif
}