/
X509AsymmetricSecurityKey.cs
448 lines (389 loc) · 18.8 KB
/
X509AsymmetricSecurityKey.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
// 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.
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.ServiceModel;
namespace System.IdentityModel.Tokens
{
public class X509AsymmetricSecurityKey : AsymmetricSecurityKey
{
private X509Certificate2 _certificate;
private AsymmetricAlgorithm _privateKey;
private bool _privateKeyAvailabilityDetermined;
private AsymmetricAlgorithm _publicKey;
private bool _publicKeyAvailabilityDetermined;
public X509AsymmetricSecurityKey(X509Certificate2 certificate)
{
_certificate = certificate ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(certificate));
}
public override int KeySize
{
get { return PublicKey.KeySize; }
}
private AsymmetricAlgorithm PrivateKey
{
get
{
if (!_privateKeyAvailabilityDetermined)
{
lock (ThisLock)
{
_privateKey = _certificate.GetRSAPrivateKey();
if (_privateKey is not null)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// TODO: Investigate if this code is still needed or if there's a way to do the same thing without RSACryptoServiceProvider
RSACryptoServiceProvider rsaCsp = _privateKey as RSACryptoServiceProvider;
// ProviderType == 1 is PROV_RSA_FULL provider type that only supports SHA1. Change it to PROV_RSA_AES=24 that supports SHA2 also.
if (rsaCsp != null && rsaCsp.CspKeyContainerInfo.ProviderType == 1)
{
CspParameters csp = new CspParameters();
csp.ProviderType = 24;
csp.KeyContainerName = rsaCsp.CspKeyContainerInfo.KeyContainerName;
csp.KeyNumber = (int)rsaCsp.CspKeyContainerInfo.KeyNumber;
if (rsaCsp.CspKeyContainerInfo.MachineKeyStore)
{
csp.Flags = CspProviderFlags.UseMachineKeyStore;
}
csp.Flags |= CspProviderFlags.UseExistingKey;
_privateKey = new RSACryptoServiceProvider(csp);
}
}
}
else
{
_privateKey = _certificate.GetDSAPrivateKey();
_privateKey ??= _certificate.GetECDsaPrivateKey();
}
if (_certificate.HasPrivateKey && _privateKey == null)
{
DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.PrivateKeyNotSupported));
}
_privateKeyAvailabilityDetermined = true;
}
}
return _privateKey;
}
}
private AsymmetricAlgorithm PublicKey
{
get
{
if (!_publicKeyAvailabilityDetermined)
{
lock (ThisLock)
{
if (!_publicKeyAvailabilityDetermined)
{
_publicKey = _certificate.GetRSAPublicKey();
if (_publicKey == null)
{
// Need DSACertificateExtensions to support DSA certificate which is in netstandard2.1 and netcore2.0. As we target netstandard2.0, we don't
// have access to DSACertificateExtensions
DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.PublicKeyNotSupported));
}
_publicKeyAvailabilityDetermined = true;
}
}
}
return _publicKey;
}
}
private Object ThisLock { get; } = new Object();
public override byte[] DecryptKey(string algorithm, byte[] keyData)
{
throw ExceptionHelper.PlatformNotSupported();
}
public override byte[] EncryptKey(string algorithm, byte[] keyData)
{
throw ExceptionHelper.PlatformNotSupported();
}
public override AsymmetricAlgorithm GetAsymmetricAlgorithm(string algorithm, bool privateKey)
{
if (privateKey)
{
if (PrivateKey == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.MissingPrivateKey));
}
if (string.IsNullOrEmpty(algorithm))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SRP.Format(SRP.EmptyOrNullArgumentString, nameof(algorithm)));
}
switch (algorithm)
{
case SignedXml.XmlDsigDSAUrl:
if ((PrivateKey as DSA) != null)
{
return (PrivateKey as DSA);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.AlgorithmAndPrivateKeyMisMatch));
case SignedXml.XmlDsigRSASHA1Url:
case SecurityAlgorithms.RsaSha256Signature:
case EncryptedXml.XmlEncRSA15Url:
case EncryptedXml.XmlEncRSAOAEPUrl:
if ((PrivateKey as RSA) != null)
{
return (PrivateKey as RSA);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.AlgorithmAndPrivateKeyMisMatch));
default:
if (IsSupportedAlgorithm(algorithm))
{
return PrivateKey;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.Format(SRP.UnsupportedCryptoAlgorithm, algorithm)));
}
}
}
else
{
switch (algorithm)
{
case SignedXml.XmlDsigDSAUrl:
if (PublicKey is DSA dsaPrivateKey)
{
return dsaPrivateKey;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.AlgorithmAndPublicKeyMisMatch));
case SignedXml.XmlDsigRSASHA1Url:
case SecurityAlgorithms.RsaSha256Signature:
case EncryptedXml.XmlEncRSA15Url:
case EncryptedXml.XmlEncRSAOAEPUrl:
if ((PublicKey as RSA) != null)
{
return (PublicKey as RSA);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.AlgorithmAndPublicKeyMisMatch));
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.Format(SRP.UnsupportedCryptoAlgorithm, algorithm)));
}
}
}
public override HashAlgorithm GetHashAlgorithmForSignature(string algorithm)
{
if (string.IsNullOrEmpty(algorithm))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SRP.Format(SRP.EmptyOrNullArgumentString, nameof(algorithm)));
}
object algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm);
if (algorithmObject != null)
{
SignatureDescription description = algorithmObject as SignatureDescription;
if (description != null)
{
return description.CreateDigest();
}
HashAlgorithm hashAlgorithm = algorithmObject as HashAlgorithm;
if (hashAlgorithm != null)
{
return hashAlgorithm;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SRP.Format(SRP.UnsupportedAlgorithmForCryptoOperation,
algorithm, "CreateDigest")));
}
switch (algorithm)
{
case SignedXml.XmlDsigDSAUrl:
case SignedXml.XmlDsigRSASHA1Url:
return CryptoHelper.NewSha1HashAlgorithm();
case SecurityAlgorithms.RsaSha256Signature:
return CryptoHelper.NewSha256HashAlgorithm();
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.Format(SRP.UnsupportedCryptoAlgorithm, algorithm)));
}
}
public override AsymmetricSignatureDeformatter GetSignatureDeformatter(string algorithm)
{
// We support one of the two algoritms, but not both.
// XmlDsigDSAUrl = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
// XmlDsigRSASHA1Url = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
if (string.IsNullOrEmpty(algorithm))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SRP.Format(SRP.EmptyOrNullArgumentString, nameof(algorithm)));
}
object algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm);
if (algorithmObject != null)
{
SignatureDescription description = algorithmObject as SignatureDescription;
if (description != null)
{
return description.CreateDeformatter(PublicKey);
}
try
{
AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = algorithmObject as AsymmetricSignatureDeformatter;
if (asymmetricSignatureDeformatter != null)
{
asymmetricSignatureDeformatter.SetKey(PublicKey);
return asymmetricSignatureDeformatter;
}
}
catch (InvalidCastException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.AlgorithmAndPublicKeyMisMatch, e));
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SRP.Format(SRP.UnsupportedAlgorithmForCryptoOperation,
algorithm, nameof(GetSignatureDeformatter))));
}
switch (algorithm)
{
case SignedXml.XmlDsigDSAUrl:
// Ensure that we have a DSA algorithm object.
DSA dsa = (PublicKey as DSA);
if (dsa == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.PublicKeyNotDSA));
}
return new DSASignatureDeformatter(dsa);
case SignedXml.XmlDsigRSASHA1Url:
case SecurityAlgorithms.RsaSha256Signature:
// Ensure that we have an RSA algorithm object.
RSA rsa = (PublicKey as RSA);
if (rsa == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.PublicKeyNotRSA));
}
return new RSAPKCS1SignatureDeformatter(rsa);
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.Format(SRP.UnsupportedCryptoAlgorithm, algorithm)));
}
}
public override AsymmetricSignatureFormatter GetSignatureFormatter(string algorithm)
{
// One can sign only if the private key is present.
if (PrivateKey == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.MissingPrivateKey));
}
if (string.IsNullOrEmpty(algorithm))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SRP.Format(SRP.EmptyOrNullArgumentString, nameof(algorithm)));
}
// We support:
// XmlDsigDSAUrl = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
// XmlDsigRSASHA1Url = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
// RsaSha256Signature = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
AsymmetricAlgorithm privateKey = PrivateKey;
object algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm);
if (algorithmObject != null)
{
SignatureDescription description = algorithmObject as SignatureDescription;
if (description != null)
{
return description.CreateFormatter(privateKey);
}
try
{
AsymmetricSignatureFormatter asymmetricSignatureFormatter = algorithmObject as AsymmetricSignatureFormatter;
if (asymmetricSignatureFormatter != null)
{
asymmetricSignatureFormatter.SetKey(privateKey);
return asymmetricSignatureFormatter;
}
}
catch (InvalidCastException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.AlgorithmAndPrivateKeyMisMatch, e));
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SRP.Format(SRP.UnsupportedAlgorithmForCryptoOperation,
algorithm, nameof(GetSignatureFormatter))));
}
switch (algorithm)
{
case SignedXml.XmlDsigDSAUrl:
// Ensure that we have a DSA algorithm object.
DSA dsa = (PrivateKey as DSA);
if (dsa == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.PrivateKeyNotDSA));
}
#pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
return new DSASignatureFormatter(dsa);
#pragma warning restore CA5351 // Do Not Use Broken Cryptographic Algorithms
case SignedXml.XmlDsigRSASHA1Url:
// Ensure that we have an RSA algorithm object.
RSA rsa = (PrivateKey as RSA);
if (rsa == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.PrivateKeyNotRSA));
}
return new RSAPKCS1SignatureFormatter(rsa);
case SecurityAlgorithms.RsaSha256Signature:
// Ensure that we have an RSA algorithm object.
RSA rsaSha256 = (privateKey as RSA);
if (rsaSha256 == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.PrivateKeyNotRSA));
}
return new RSAPKCS1SignatureFormatter(rsaSha256);
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.Format(SRP.UnsupportedCryptoAlgorithm, algorithm)));
}
}
public override bool HasPrivateKey()
{
return (PrivateKey != null);
}
public override bool IsAsymmetricAlgorithm(string algorithm)
{
if (string.IsNullOrEmpty(algorithm))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SRP.Format(SRP.EmptyOrNullArgumentString, nameof(algorithm)));
}
return (CryptoHelper.IsAsymmetricAlgorithm(algorithm));
}
public override bool IsSupportedAlgorithm(string algorithm)
{
if (string.IsNullOrEmpty(algorithm))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SRP.Format(SRP.EmptyOrNullArgumentString, nameof(algorithm)));
}
object algorithmObject = null;
try
{
algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm);
}
catch (InvalidOperationException)
{
algorithm = null;
}
if (algorithmObject != null)
{
SignatureDescription signatureDescription = algorithmObject as SignatureDescription;
if (signatureDescription != null)
{
return true;
}
AsymmetricAlgorithm asymmetricAlgorithm = algorithmObject as AsymmetricAlgorithm;
if (asymmetricAlgorithm != null)
{
return true;
}
return false;
}
switch (algorithm)
{
case SignedXml.XmlDsigDSAUrl:
return (PublicKey is DSA);
case SignedXml.XmlDsigRSASHA1Url:
case SecurityAlgorithms.RsaSha256Signature:
case EncryptedXml.XmlEncRSA15Url:
case EncryptedXml.XmlEncRSAOAEPUrl:
return (PublicKey is RSA);
default:
return false;
}
}
public override bool IsSymmetricAlgorithm(string algorithm)
{
return CryptoHelper.IsSymmetricAlgorithm(algorithm);
}
}
}