/
CngKey.cs
863 lines (728 loc) · 36 KB
/
CngKey.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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography {
/// <summary>
/// Flags providing information about a raw key handle being opened
/// </summary>
[Flags]
public enum CngKeyHandleOpenOptions {
None = 0x00000000,
/// <summary>
/// The key handle being opened represents an ephemeral key
/// </summary>
EphemeralKey = 0x00000001
}
/// <summary>
/// Managed representation of an NCrypt key
/// </summary>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed partial class CngKey : IDisposable {
private SafeNCryptKeyHandle m_keyHandle;
private SafeNCryptProviderHandle m_kspHandle;
[System.Security.SecurityCritical]
private CngKey(SafeNCryptProviderHandle kspHandle, SafeNCryptKeyHandle keyHandle) {
Contract.Requires(keyHandle != null && !keyHandle.IsInvalid && !keyHandle.IsClosed);
Contract.Requires(kspHandle != null && !kspHandle.IsInvalid && !kspHandle.IsClosed);
Contract.Ensures(m_keyHandle != null && !m_keyHandle.IsInvalid && !m_keyHandle.IsClosed);
Contract.Ensures(kspHandle != null && !kspHandle.IsInvalid && !kspHandle.IsClosed);
m_keyHandle = keyHandle;
m_kspHandle = kspHandle;
}
//
// Key properties
//
/// <summary>
/// Algorithm group this key can be used with
/// </summary>
public CngAlgorithmGroup AlgorithmGroup {
[SecuritySafeCritical]
[Pure]
get {
Contract.Assert(m_keyHandle != null);
string group = NCryptNative.GetPropertyAsString(m_keyHandle,
NCryptNative.KeyPropertyName.AlgorithmGroup,
CngPropertyOptions.None);
if (group == null) {
return null;
}
else {
return new CngAlgorithmGroup(group);
}
}
}
/// <summary>
/// Name of the algorithm this key can be used with
/// </summary>
public CngAlgorithm Algorithm {
[SecuritySafeCritical]
get {
Contract.Assert(m_keyHandle != null);
string algorithm = NCryptNative.GetPropertyAsString(m_keyHandle,
NCryptNative.KeyPropertyName.Algorithm,
CngPropertyOptions.None);
return new CngAlgorithm(algorithm);
}
}
/// <summary>
/// Export restrictions on the key
/// </summary>
public CngExportPolicies ExportPolicy {
[SecuritySafeCritical]
get {
Contract.Assert(m_keyHandle != null);
int policy = NCryptNative.GetPropertyAsDWord(m_keyHandle,
NCryptNative.KeyPropertyName.ExportPolicy,
CngPropertyOptions.None);
return (CngExportPolicies)policy;
}
internal set {
var property = new CngProperty(
NCryptNative.KeyPropertyName.ExportPolicy,
BitConverter.GetBytes((int)value),
CngPropertyOptions.Persist);
SetProperty(property);
}
}
/// <summary>
/// Native handle for the key
/// </summary>
public SafeNCryptKeyHandle Handle {
[System.Security.SecurityCritical]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
get {
Contract.Assert(m_keyHandle != null);
return m_keyHandle.Duplicate();
}
}
/// <summary>
/// Is this key ephemeral or persisted
/// </summary>
/// <remarks>
/// Any ephemeral key created by the CLR will have a property 'CLR IsEphemeral' which consists
/// of a single byte containing the value 1. We cannot detect ephemeral keys created by other
/// APIs and imported via handle.
/// </remarks>
public bool IsEphemeral {
[SecuritySafeCritical]
[Pure]
get {
Contract.Assert(m_keyHandle != null);
bool foundProperty;
byte[] ephemeralProperty = null;
try {
ephemeralProperty = NCryptNative.GetProperty(m_keyHandle,
NCryptNative.KeyPropertyName.ClrIsEphemeral,
CngPropertyOptions.CustomProperty,
out foundProperty);
}
catch (CryptographicException) {
// Third party Key providers, and Windows PCP KSP won't recognize this property;
// and Win32 layer does not enforce error return contract.
// Therefore, they can return whatever error code they think appropriate.
return false;
}
return foundProperty &&
ephemeralProperty != null &&
ephemeralProperty.Length == 1 &&
ephemeralProperty[0] == 1;
}
[System.Security.SecurityCritical]
private set {
Contract.Assert(m_keyHandle != null);
NCryptNative.SetProperty(m_keyHandle,
NCryptNative.KeyPropertyName.ClrIsEphemeral,
new byte[] { value ? (byte)1 : (byte)0 },
CngPropertyOptions.CustomProperty);
}
}
/// <summary>
/// Is this a machine key or a user key
/// </summary>
public bool IsMachineKey {
[SecuritySafeCritical]
get {
Contract.Assert(m_keyHandle != null);
int type = NCryptNative.GetPropertyAsDWord(m_keyHandle,
NCryptNative.KeyPropertyName.KeyType,
CngPropertyOptions.None);
return ((CngKeyTypes)type & CngKeyTypes.MachineKey) == CngKeyTypes.MachineKey;
}
}
/// <summary>
/// The name of the key, null if it is ephemeral. We can only detect ephemeral keys created by
/// the CLR. Other ephemeral keys, such as those imported by handle, will get a CryptographicException
/// if they read this property.
/// </summary>
public string KeyName {
[SecuritySafeCritical]
get {
Contract.Assert(m_keyHandle != null);
if (IsEphemeral) {
return null;
}
else {
return NCryptNative.GetPropertyAsString(m_keyHandle,
NCryptNative.KeyPropertyName.Name,
CngPropertyOptions.None);
}
}
}
/// <summary>
/// Size, in bits, of the key
/// </summary>
public int KeySize {
[SecuritySafeCritical]
get {
Contract.Assert(m_keyHandle != null);
// First, try the Win10+ Public Key Length property, it matches the purpose
// of this property better when it and Length disagree.
int keySize = 0;
NCryptNative.ErrorCode errorCode = NCryptNative.GetPropertyAsInt(
m_keyHandle,
NCryptNative.KeyPropertyName.PublicKeyLength,
CngPropertyOptions.None,
ref keySize);
// If the new property reports it was successful, use it.
// Otherwise, ask the old question.
if (errorCode == NCryptNative.ErrorCode.Success) {
return keySize;
}
return NCryptNative.GetPropertyAsDWord(m_keyHandle,
NCryptNative.KeyPropertyName.Length,
CngPropertyOptions.None);
}
}
/// <summary>
/// Usage restrictions on the key
/// </summary>
public CngKeyUsages KeyUsage {
[SecuritySafeCritical]
get {
Contract.Assert(m_keyHandle != null);
int keyUsage = NCryptNative.GetPropertyAsDWord(m_keyHandle,
NCryptNative.KeyPropertyName.KeyUsage,
CngPropertyOptions.None);
return (CngKeyUsages)keyUsage;
}
}
/// <summary>
/// HWND of the window to use as a parent for any UI
/// </summary>
public IntPtr ParentWindowHandle {
[SecuritySafeCritical]
get {
Contract.Assert(m_keyHandle != null);
return NCryptNative.GetPropertyAsIntPtr(m_keyHandle,
NCryptNative.KeyPropertyName.ParentWindowHandle,
CngPropertyOptions.None);
}
[SecuritySafeCritical]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
set {
Contract.Assert(m_keyHandle != null);
NCryptNative.SetProperty(m_keyHandle,
NCryptNative.KeyPropertyName.ParentWindowHandle,
value,
CngPropertyOptions.None);
}
}
/// <summary>
/// KSP which holds this key
/// </summary>
public CngProvider Provider {
[SecuritySafeCritical]
get {
Contract.Assert(m_kspHandle != null);
string provider = NCryptNative.GetPropertyAsString(m_kspHandle,
NCryptNative.ProviderPropertyName.Name,
CngPropertyOptions.None);
if (provider == null) {
return null;
}
else {
return new CngProvider(provider);
}
}
}
/// <summary>
/// Native handle to the KSP associated with this key
/// </summary>
public SafeNCryptProviderHandle ProviderHandle {
[System.Security.SecurityCritical]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
get {
Contract.Assert(m_kspHandle != null);
return m_kspHandle.Duplicate();
}
}
/// <summary>
/// Unique name of the key, null if it is ephemeral. See the comments on the Name property for
/// details about names of ephemeral keys.
/// </summary>
public string UniqueName {
[SecuritySafeCritical]
get {
Contract.Assert(m_keyHandle != null);
if (IsEphemeral) {
return null;
}
else {
return NCryptNative.GetPropertyAsString(m_keyHandle,
NCryptNative.KeyPropertyName.UniqueName,
CngPropertyOptions.None);
}
}
}
/// <summary>
/// UI strings associated with a key
/// </summary>
public CngUIPolicy UIPolicy {
[SecuritySafeCritical]
get {
Contract.Ensures(Contract.Result<CngUIPolicy>() != null);
Contract.Assert(m_keyHandle != null);
NCryptNative.NCRYPT_UI_POLICY uiPolicy =
NCryptNative.GetPropertyAsStruct<NCryptNative.NCRYPT_UI_POLICY>(m_keyHandle,
NCryptNative.KeyPropertyName.UIPolicy,
CngPropertyOptions.None);
string useContext = NCryptNative.GetPropertyAsString(m_keyHandle,
NCryptNative.KeyPropertyName.UseContext,
CngPropertyOptions.None);
return new CngUIPolicy(uiPolicy.dwFlags,
uiPolicy.pszFriendlyName,
uiPolicy.pszDescription,
useContext,
uiPolicy.pszCreationTitle);
}
}
/// <summary>
/// Build a key container permission for the specified access to this key
///
/// If the key is a known ephemeral key, return null, since we don't require permission to work with
/// those keys. Otherwise return a permission scoped to the specific key and ksp if we can get those
/// values, defaulting back to a full KeyContainerPermission if we cannot.
/// </summary>
[SecuritySafeCritical]
[SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity", Justification = "The demand is based on a non-mutable value type")]
internal KeyContainerPermission BuildKeyContainerPermission(KeyContainerPermissionFlags flags) {
Contract.Ensures(Contract.Result<KeyContainerPermission>() != null || IsEphemeral);
Contract.Assert(m_keyHandle != null);
Contract.Assert(m_kspHandle != null);
KeyContainerPermission permission = null;
if (!IsEphemeral) {
// Try to get the name of the key and ksp to demand for this specific instance
string keyName = null;
string kspName = null;
try {
keyName = KeyName;
kspName = NCryptNative.GetPropertyAsString(m_kspHandle,
NCryptNative.ProviderPropertyName.Name,
CngPropertyOptions.None);
}
catch (CryptographicException) { /* This may have been an imported ephemeral key */ }
if (keyName != null) {
KeyContainerPermissionAccessEntry access = new KeyContainerPermissionAccessEntry(keyName, flags);
access.ProviderName = kspName;
permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
permission.AccessEntries.Add(access);
}
else {
permission = new KeyContainerPermission(flags);
}
}
return permission;
}
//
// Creation factory methods
//
public static CngKey Create(CngAlgorithm algorithm) {
Contract.Ensures(Contract.Result<CngKey>() != null);
return Create(algorithm, null);
}
public static CngKey Create(CngAlgorithm algorithm, string keyName) {
Contract.Ensures(Contract.Result<CngKey>() != null);
return Create(algorithm, keyName, null);
}
[SecuritySafeCritical]
public static CngKey Create(CngAlgorithm algorithm, string keyName, CngKeyCreationParameters creationParameters) {
Contract.Ensures(Contract.Result<CngKey>() != null);
if (algorithm == null) {
throw new ArgumentNullException("algorithm");
}
if (creationParameters == null) {
creationParameters = new CngKeyCreationParameters();
}
// Make sure that NCrypt is supported on this platform
if (!NCryptNative.NCryptSupported) {
throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
}
// If we're not creating an ephemeral key, then we need to ensure the user has access to the key name
if (keyName != null) {
KeyContainerPermissionAccessEntry access = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Create);
access.ProviderName = creationParameters.Provider.Provider;
KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
permission.AccessEntries.Add(access);
permission.Demand();
}
//
// Create the native handles representing the new key, setup the creation parameters on it, and
// finalize it for use.
//
SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(creationParameters.Provider.Provider);
SafeNCryptKeyHandle keyHandle = NCryptNative.CreatePersistedKey(kspHandle,
algorithm.Algorithm,
keyName,
creationParameters.KeyCreationOptions);
SetKeyProperties(keyHandle, creationParameters);
NCryptNative.FinalizeKey(keyHandle);
CngKey key = new CngKey(kspHandle, keyHandle);
// No name translates to an ephemeral key
if (keyName == null) {
key.IsEphemeral = true;
}
return key;
}
/// <summary>
/// Delete this key
/// </summary>
[SecuritySafeCritical]
public void Delete() {
Contract.Assert(m_keyHandle != null);
// Make sure we have permission to delete this key
KeyContainerPermission permission = BuildKeyContainerPermission(KeyContainerPermissionFlags.Delete);
if (permission != null) {
permission.Demand();
}
NCryptNative.DeleteKey(m_keyHandle);
// Once the key is deleted, the handles are no longer valid so dispose of this instance
Dispose();
}
[SecuritySafeCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")]
public void Dispose() {
if (m_kspHandle != null) {
m_kspHandle.Dispose();
}
if (m_keyHandle != null) {
m_keyHandle.Dispose();
}
}
//
// Check to see if a key already exists
//
public static bool Exists(string keyName) {
return Exists(keyName, CngProvider.MicrosoftSoftwareKeyStorageProvider);
}
public static bool Exists(string keyName, CngProvider provider) {
return Exists(keyName, provider, CngKeyOpenOptions.None);
}
[SecuritySafeCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")]
public static bool Exists(string keyName, CngProvider provider, CngKeyOpenOptions options) {
if (keyName == null) {
throw new ArgumentNullException("keyName");
}
if (provider == null) {
throw new ArgumentNullException("provider");
}
// Make sure that NCrypt is supported on this platform
if (!NCryptNative.NCryptSupported) {
throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
}
using (SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider)) {
SafeNCryptKeyHandle keyHandle = null;
try {
NCryptNative.ErrorCode error = NCryptNative.UnsafeNativeMethods.NCryptOpenKey(kspHandle,
out keyHandle,
keyName,
0,
options);
// CNG will return either NTE_NOT_FOUND or NTE_BAD_KEYSET for the case where the key does
// not exist, so we need to check for both return codes.
bool keyNotFound = error == NCryptNative.ErrorCode.KeyDoesNotExist ||
error == NCryptNative.ErrorCode.NotFound;
if (error != NCryptNative.ErrorCode.Success && !keyNotFound) {
throw new CryptographicException((int)error);
}
return error == NCryptNative.ErrorCode.Success;
}
finally {
if (keyHandle != null) {
keyHandle.Dispose();
}
}
}
}
//
// Import factory methods
//
public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format) {
Contract.Ensures(Contract.Result<CngKey>() != null);
return Import(keyBlob, format, CngProvider.MicrosoftSoftwareKeyStorageProvider);
}
internal static CngKey Import(byte[] keyBlob, string curveName, CngKeyBlobFormat format) {
Contract.Ensures(Contract.Result<CngKey>() != null);
return Import(keyBlob, curveName, format, CngProvider.MicrosoftSoftwareKeyStorageProvider);
}
public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format, CngProvider provider) {
Contract.Ensures(Contract.Result<CngKey>() != null);
return Import(keyBlob, null, format, provider);
}
[SecuritySafeCritical]
internal static CngKey Import(byte[] keyBlob, string curveName, CngKeyBlobFormat format, CngProvider provider)
{
Contract.Ensures(Contract.Result<CngKey>() != null);
if (keyBlob == null) {
throw new ArgumentNullException("keyBlob");
}
if (format == null) {
throw new ArgumentNullException("format");
}
if (provider == null) {
throw new ArgumentNullException("provider");
}
// Make sure that NCrypt is supported on this platform
if (!NCryptNative.NCryptSupported) {
throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
}
// If we don't know for sure that the key will be ephemeral, then we need to demand Import
// permission. Since we won't know the name of the key until it's too late, we demand a full Import
// rather than one scoped to the key.
bool safeKeyImport = format == CngKeyBlobFormat.EccPublicBlob ||
format == CngKeyBlobFormat.EccFullPublicBlob ||
format == CngKeyBlobFormat.GenericPublicBlob;
if (!safeKeyImport) {
new KeyContainerPermission(KeyContainerPermissionFlags.Import).Demand();
}
// Import the key into the KSP
SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider);
SafeNCryptKeyHandle keyHandle;
if (curveName == null) {
keyHandle = NCryptNative.ImportKey(kspHandle, keyBlob, format.Format);
} else {
keyHandle = ECCng.ImportKeyBlob(format.Format, keyBlob, curveName, kspHandle);
}
// Prepare the key for use
CngKey key = new CngKey(kspHandle, keyHandle);
// We can't tell directly if an OpaqueTransport blob imported as an ephemeral key or not
key.IsEphemeral = format != CngKeyBlobFormat.OpaqueTransportBlob;
return key;
}
/// <summary>
/// Export the key out of the KSP
/// </summary>
[SecuritySafeCritical]
public byte[] Export(CngKeyBlobFormat format) {
Contract.Assert(m_keyHandle != null);
if (format == null) {
throw new ArgumentNullException("format");
}
KeyContainerPermission permission = BuildKeyContainerPermission(KeyContainerPermissionFlags.Export);
if (permission != null) {
permission.Demand();
}
return NCryptNative.ExportKey(m_keyHandle, format.Format);
}
/// <summary>
/// Get the value of an arbitrary property
/// </summary>
[SecuritySafeCritical]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
public CngProperty GetProperty(string name, CngPropertyOptions options) {
Contract.Assert(m_keyHandle != null);
if (name == null) {
throw new ArgumentNullException("name");
}
bool foundProperty;
byte[] value = NCryptNative.GetProperty(m_keyHandle, name, options, out foundProperty);
if (!foundProperty) {
throw new CryptographicException((int)NCryptNative.ErrorCode.NotFound);
}
return new CngProperty(name, value, options);
}
/// <summary>
/// Determine if a property exists on the key
/// </summary>
[SecuritySafeCritical]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
public bool HasProperty(string name, CngPropertyOptions options) {
Contract.Assert(m_keyHandle != null);
if (name == null) {
throw new ArgumentNullException("name");
}
bool foundProperty;
NCryptNative.GetProperty(m_keyHandle, name, options, out foundProperty);
return foundProperty;
}
//
// Open factory methods
//
public static CngKey Open(string keyName) {
Contract.Ensures(Contract.Result<CngKey>() != null);
return Open(keyName, CngProvider.MicrosoftSoftwareKeyStorageProvider);
}
public static CngKey Open(string keyName, CngProvider provider) {
Contract.Ensures(Contract.Result<CngKey>() != null);
return Open(keyName, provider, CngKeyOpenOptions.None);
}
[SecuritySafeCritical]
public static CngKey Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions) {
Contract.Ensures(Contract.Result<CngKey>() != null);
if (keyName == null) {
throw new ArgumentNullException("keyName");
}
if (provider == null) {
throw new ArgumentNullException("provider");
}
// Make sure that NCrypt is supported on this platform
if (!NCryptNative.NCryptSupported) {
throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
}
// Ensure the user has access to the key name
KeyContainerPermissionAccessEntry access = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Open);
access.ProviderName = provider.Provider;
KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
permission.AccessEntries.Add(access);
permission.Demand();
// Open the key
SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider);
SafeNCryptKeyHandle keyHandle = NCryptNative.OpenKey(kspHandle, keyName, openOptions);
return new CngKey(kspHandle, keyHandle);
}
/// <summary>
/// Wrap an existing key handle with a CngKey object
/// </summary>
[System.Security.SecurityCritical]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
public static CngKey Open(SafeNCryptKeyHandle keyHandle, CngKeyHandleOpenOptions keyHandleOpenOptions) {
if (keyHandle == null) {
throw new ArgumentNullException("keyHandle");
}
if (keyHandle.IsClosed || keyHandle.IsInvalid) {
throw new ArgumentException(SR.GetString(SR.Cryptography_OpenInvalidHandle), "keyHandle");
}
SafeNCryptKeyHandle keyHandleCopy = keyHandle.Duplicate();
// Get a handle to the key's KSP
SafeNCryptProviderHandle kspHandle = new SafeNCryptProviderHandle();
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally {
IntPtr rawHandle = NCryptNative.GetPropertyAsIntPtr(keyHandle,
NCryptNative.KeyPropertyName.ProviderHandle,
CngPropertyOptions.None);
kspHandle.SetHandleValue (rawHandle);
}
// Setup a key object wrapping the handle
CngKey key = null;
bool keyFullySetup = false;
try {
key = new CngKey(kspHandle, keyHandleCopy);
bool openingEphemeralKey = (keyHandleOpenOptions & CngKeyHandleOpenOptions.EphemeralKey) == CngKeyHandleOpenOptions.EphemeralKey;
//
// If we're wrapping a handle to an ephemeral key, we need to make sure that IsEphemeral is
// setup to return true. In the case that the handle is for an ephemeral key that was created
// by the CLR, then we don't have anything to do as the IsEphemeral CLR property will already
// be setup. However, if the key was created outside of the CLR we will need to setup our
// ephemeral detection property.
//
// This enables consumers of CngKey objects to always be able to rely on the result of
// calling IsEphemeral, and also allows them to safely access the Name property.
//
// Finally, if we detect that this is an ephemeral key that the CLR created but we were not
// told that it was an ephemeral key we'll throw an exception. This prevents us from having
// to decide who to believe -- the key property or the caller of the API. Since other code
// relies on the ephemeral flag being set properly to avoid tripping over bugs in CNG, we
// need to reject the case that we suspect that the flag is incorrect.
//
if (!key.IsEphemeral && openingEphemeralKey) {
key.IsEphemeral = true;
}
else if (key.IsEphemeral && !openingEphemeralKey) {
throw new ArgumentException(SR.GetString(SR.Cryptography_OpenEphemeralKeyHandleWithoutEphemeralFlag), "keyHandleOpenOptions");
}
keyFullySetup = true;
}
finally {
// Make sure that we don't leak the handle the CngKey duplicated
if (!keyFullySetup && key != null) {
key.Dispose();
}
}
return key;
}
/// <summary>
/// Setup the key properties specified in the key creation parameters
/// </summary>
/// <param name="keyHandle"></param>
/// <param name="creationParameters"></param>
[System.Security.SecurityCritical]
private static void SetKeyProperties(SafeNCryptKeyHandle keyHandle,
CngKeyCreationParameters creationParameters) {
Contract.Requires(keyHandle != null && !keyHandle.IsInvalid && !keyHandle.IsClosed);
Contract.Requires(creationParameters != null);
//
// Setup the well-known properties.
//
if (creationParameters.ExportPolicy.HasValue) {
NCryptNative.SetProperty(keyHandle,
NCryptNative.KeyPropertyName.ExportPolicy,
(int)creationParameters.ExportPolicy.Value,
CngPropertyOptions.Persist);
}
if (creationParameters.KeyUsage.HasValue) {
NCryptNative.SetProperty(keyHandle,
NCryptNative.KeyPropertyName.KeyUsage,
(int)creationParameters.KeyUsage.Value,
CngPropertyOptions.Persist);
}
if (creationParameters.ParentWindowHandle != IntPtr.Zero) {
NCryptNative.SetProperty(keyHandle,
NCryptNative.KeyPropertyName.ParentWindowHandle,
creationParameters.ParentWindowHandle,
CngPropertyOptions.None);
}
if (creationParameters.UIPolicy != null) {
NCryptNative.NCRYPT_UI_POLICY uiPolicy = new NCryptNative.NCRYPT_UI_POLICY();
uiPolicy.dwVersion = 1;
uiPolicy.dwFlags = creationParameters.UIPolicy.ProtectionLevel;
uiPolicy.pszCreationTitle = creationParameters.UIPolicy.CreationTitle;
uiPolicy.pszFriendlyName = creationParameters.UIPolicy.FriendlyName;
uiPolicy.pszDescription = creationParameters.UIPolicy.Description;
NCryptNative.SetProperty(keyHandle,
NCryptNative.KeyPropertyName.UIPolicy,
uiPolicy,
CngPropertyOptions.Persist);
// The use context is a seperate property from the standard UI context
if (creationParameters.UIPolicy.UseContext != null) {
NCryptNative.SetProperty(keyHandle,
NCryptNative.KeyPropertyName.UseContext,
creationParameters.UIPolicy.UseContext,
CngPropertyOptions.Persist);
}
}
// Iterate over the custom properties, setting those as well.
foreach (CngProperty property in creationParameters.ParametersNoDemand) {
NCryptNative.SetProperty(keyHandle, property.Name, property.Value, property.Options);
}
}
/// <summary>
/// Set an arbitrary property on the key
/// </summary>
[SecuritySafeCritical]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
public void SetProperty(CngProperty property) {
Contract.Assert(m_keyHandle != null);
NCryptNative.SetProperty(m_keyHandle, property.Name, property.Value, property.Options);
}
}
}