-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
Copy pathCryptoUtils.cs
1582 lines (1352 loc) · 54.6 KB
/
CryptoUtils.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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Text;
using System.Security;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.ConstrainedExecution;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.CodeAnalysis;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Remoting;
namespace System.Management.Automation.Internal
{
/// <summary>
/// Class that encapsulates native crypto provider handles and provides a
/// mechanism for resources released by them.
/// </summary>
// [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)]
// [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
internal class PSSafeCryptProvHandle : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// This safehandle instance "owns" the handle, hence base(true)
/// is being called. When safehandle is no longer in use it will
/// call this class's ReleaseHandle method which will release
/// the resources.
/// </summary>
internal PSSafeCryptProvHandle() : base(true) { }
/// <summary>
/// Release the crypto handle held by this instance.
/// </summary>
/// <returns>True on success, false otherwise.</returns>
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected override bool ReleaseHandle()
{
return PSCryptoNativeUtils.CryptReleaseContext(handle, 0);
}
}
/// <summary>
/// Class the encapsulates native crypto key handles and provides a
/// mechanism to release resources used by it.
/// </summary>
// [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)]
// [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
internal class PSSafeCryptKey : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// This safehandle instance "owns" the handle, hence base(true)
/// is being called. When safehandle is no longer in use it will
/// call this class's ReleaseHandle method which will release the
/// resources.
/// </summary>
internal PSSafeCryptKey() : base(true) { }
/// <summary>
/// Release the crypto handle held by this instance.
/// </summary>
/// <returns>True on success, false otherwise.</returns>
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected override bool ReleaseHandle()
{
return PSCryptoNativeUtils.CryptDestroyKey(handle);
}
/// <summary>
/// Equivalent of IntPtr.Zero for the safe crypt key.
/// </summary>
internal static PSSafeCryptKey Zero { get; } = new PSSafeCryptKey();
}
/// <summary>
/// This class provides the wrapper for all Native CAPI functions.
/// </summary>
internal class PSCryptoNativeUtils
{
#region Functions
#if UNIX
/// Return Type: BOOL->int
///hProv: HCRYPTPROV->ULONG_PTR->unsigned int
///Algid: ALG_ID->unsigned int
///dwFlags: DWORD->unsigned int
///phKey: HCRYPTKEY*
public static bool CryptGenKey(
PSSafeCryptProvHandle hProv,
uint Algid,
uint dwFlags,
ref PSSafeCryptKey phKey)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
public static bool CryptDestroyKey(IntPtr hKey)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///phProv: HCRYPTPROV*
///szContainer: LPCWSTR->WCHAR*
///szProvider: LPCWSTR->WCHAR*
///dwProvType: DWORD->unsigned int
///dwFlags: DWORD->unsigned int
public static bool CryptAcquireContext(ref PSSafeCryptProvHandle phProv,
[InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string szContainer,
[InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string szProvider,
uint dwProvType,
uint dwFlags)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hProv: HCRYPTPROV->ULONG_PTR->unsigned int
///dwFlags: DWORD->unsigned int
public static bool CryptReleaseContext(IntPtr hProv, uint dwFlags)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///hHash: HCRYPTHASH->ULONG_PTR->unsigned int
///Final: BOOL->int
///dwFlags: DWORD->unsigned int
///pbData: BYTE*
///pdwDataLen: DWORD*
///dwBufLen: DWORD->unsigned int
public static bool CryptEncrypt(PSSafeCryptKey hKey,
IntPtr hHash,
[MarshalAsAttribute(UnmanagedType.Bool)] bool Final,
uint dwFlags,
byte[] pbData,
ref int pdwDataLen,
int dwBufLen)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///hHash: HCRYPTHASH->ULONG_PTR->unsigned int
///Final: BOOL->int
///dwFlags: DWORD->unsigned int
///pbData: BYTE*
///pdwDataLen: DWORD*
public static bool CryptDecrypt(PSSafeCryptKey hKey,
IntPtr hHash,
[MarshalAsAttribute(UnmanagedType.Bool)] bool Final,
uint dwFlags,
byte[] pbData,
ref int pdwDataLen)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///hExpKey: HCRYPTKEY->ULONG_PTR->unsigned int
///dwBlobType: DWORD->unsigned int
///dwFlags: DWORD->unsigned int
///pbData: BYTE*
///pdwDataLen: DWORD*
public static bool CryptExportKey(PSSafeCryptKey hKey,
PSSafeCryptKey hExpKey,
uint dwBlobType,
uint dwFlags,
byte[] pbData,
ref uint pdwDataLen)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hProv: HCRYPTPROV->ULONG_PTR->unsigned int
///pbData: BYTE*
///dwDataLen: DWORD->unsigned int
///hPubKey: HCRYPTKEY->ULONG_PTR->unsigned int
///dwFlags: DWORD->unsigned int
///phKey: HCRYPTKEY*
public static bool CryptImportKey(PSSafeCryptProvHandle hProv,
byte[] pbData,
int dwDataLen,
PSSafeCryptKey hPubKey,
uint dwFlags,
ref PSSafeCryptKey phKey)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///pdwReserved: DWORD*
///dwFlags: DWORD->unsigned int
///phKey: HCRYPTKEY*
public static bool CryptDuplicateKey(PSSafeCryptKey hKey,
ref uint pdwReserved,
uint dwFlags,
ref PSSafeCryptKey phKey)
{
throw new PSCryptoException();
}
/// Return Type: DWORD->unsigned int
public static uint GetLastError()
{
throw new PSCryptoException();
}
#else
/// Return Type: BOOL->int
///hProv: HCRYPTPROV->ULONG_PTR->unsigned int
///Algid: ALG_ID->unsigned int
///dwFlags: DWORD->unsigned int
///phKey: HCRYPTKEY*
[DllImportAttribute(PinvokeDllNames.CryptGenKeyDllName, EntryPoint = "CryptGenKey")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptGenKey(PSSafeCryptProvHandle hProv,
uint Algid,
uint dwFlags,
ref PSSafeCryptKey phKey);
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
[DllImportAttribute(PinvokeDllNames.CryptDestroyKeyDllName, EntryPoint = "CryptDestroyKey")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptDestroyKey(IntPtr hKey);
/// Return Type: BOOL->int
///phProv: HCRYPTPROV*
///szContainer: LPCWSTR->WCHAR*
///szProvider: LPCWSTR->WCHAR*
///dwProvType: DWORD->unsigned int
///dwFlags: DWORD->unsigned int
[DllImportAttribute(PinvokeDllNames.CryptAcquireContextDllName, EntryPoint = "CryptAcquireContext")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptAcquireContext(ref PSSafeCryptProvHandle phProv,
[InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string szContainer,
[InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string szProvider,
uint dwProvType,
uint dwFlags);
/// Return Type: BOOL->int
///hProv: HCRYPTPROV->ULONG_PTR->unsigned int
///dwFlags: DWORD->unsigned int
[DllImportAttribute(PinvokeDllNames.CryptReleaseContextDllName, EntryPoint = "CryptReleaseContext")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptReleaseContext(IntPtr hProv, uint dwFlags);
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///hHash: HCRYPTHASH->ULONG_PTR->unsigned int
///Final: BOOL->int
///dwFlags: DWORD->unsigned int
///pbData: BYTE*
///pdwDataLen: DWORD*
///dwBufLen: DWORD->unsigned int
[DllImportAttribute(PinvokeDllNames.CryptEncryptDllName, EntryPoint = "CryptEncrypt")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptEncrypt(PSSafeCryptKey hKey,
IntPtr hHash,
[MarshalAsAttribute(UnmanagedType.Bool)] bool Final,
uint dwFlags,
byte[] pbData,
ref int pdwDataLen,
int dwBufLen);
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///hHash: HCRYPTHASH->ULONG_PTR->unsigned int
///Final: BOOL->int
///dwFlags: DWORD->unsigned int
///pbData: BYTE*
///pdwDataLen: DWORD*
[DllImportAttribute(PinvokeDllNames.CryptDecryptDllName, EntryPoint = "CryptDecrypt")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptDecrypt(PSSafeCryptKey hKey,
IntPtr hHash,
[MarshalAsAttribute(UnmanagedType.Bool)] bool Final,
uint dwFlags,
byte[] pbData,
ref int pdwDataLen);
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///hExpKey: HCRYPTKEY->ULONG_PTR->unsigned int
///dwBlobType: DWORD->unsigned int
///dwFlags: DWORD->unsigned int
///pbData: BYTE*
///pdwDataLen: DWORD*
[DllImportAttribute(PinvokeDllNames.CryptExportKeyDllName, EntryPoint = "CryptExportKey")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptExportKey(PSSafeCryptKey hKey,
PSSafeCryptKey hExpKey,
uint dwBlobType,
uint dwFlags,
byte[] pbData,
ref uint pdwDataLen);
/// Return Type: BOOL->int
///hProv: HCRYPTPROV->ULONG_PTR->unsigned int
///pbData: BYTE*
///dwDataLen: DWORD->unsigned int
///hPubKey: HCRYPTKEY->ULONG_PTR->unsigned int
///dwFlags: DWORD->unsigned int
///phKey: HCRYPTKEY*
[DllImportAttribute(PinvokeDllNames.CryptImportKeyDllName, EntryPoint = "CryptImportKey")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptImportKey(PSSafeCryptProvHandle hProv,
byte[] pbData,
int dwDataLen,
PSSafeCryptKey hPubKey,
uint dwFlags,
ref PSSafeCryptKey phKey);
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///pdwReserved: DWORD*
///dwFlags: DWORD->unsigned int
///phKey: HCRYPTKEY*
[DllImportAttribute(PinvokeDllNames.CryptDuplicateKeyDllName, EntryPoint = "CryptDuplicateKey")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptDuplicateKey(PSSafeCryptKey hKey,
ref uint pdwReserved,
uint dwFlags,
ref PSSafeCryptKey phKey);
/// Return Type: DWORD->unsigned int
[DllImportAttribute(PinvokeDllNames.GetLastErrorDllName, EntryPoint = "GetLastError")]
public static extern uint GetLastError();
#endif
#endregion Functions
#region Constants
/// <summary>
/// Do not use persisted private key.
/// </summary>
public const uint CRYPT_VERIFYCONTEXT = 0xF0000000;
/// <summary>
/// Mark the key for export.
/// </summary>
public const uint CRYPT_EXPORTABLE = 0x00000001;
/// <summary>
/// Automatically assign a salt value when creating a
/// session key.
/// </summary>
public const int CRYPT_CREATE_SALT = 4;
/// <summary>
/// RSA Provider.
/// </summary>
public const int PROV_RSA_FULL = 1;
/// <summary>
/// RSA Provider that supports AES
/// encryption.
/// </summary>
public const int PROV_RSA_AES = 24;
/// <summary>
/// Public key to be used for encryption.
/// </summary>
public const int AT_KEYEXCHANGE = 1;
/// <summary>
/// RSA Key.
/// </summary>
public const int CALG_RSA_KEYX =
(PSCryptoNativeUtils.ALG_CLASS_KEY_EXCHANGE |
(PSCryptoNativeUtils.ALG_TYPE_RSA | PSCryptoNativeUtils.ALG_SID_RSA_ANY));
/// <summary>
/// Create a key for encryption.
/// </summary>
public const int ALG_CLASS_KEY_EXCHANGE = (5) << (13);
/// <summary>
/// Create a RSA key pair.
/// </summary>
public const int ALG_TYPE_RSA = (2) << (9);
/// <summary>
/// </summary>
public const int ALG_SID_RSA_ANY = 0;
/// <summary>
/// Option for exporting public key blob.
/// </summary>
public const int PUBLICKEYBLOB = 6;
/// <summary>
/// Option for exporting a session key.
/// </summary>
public const int SIMPLEBLOB = 1;
/// <summary>
/// AES 256 symmetric key.
/// </summary>
public const int CALG_AES_256 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES_256);
/// <summary>
/// ALG_CLASS_DATA_ENCRYPT.
/// </summary>
public const int ALG_CLASS_DATA_ENCRYPT = (3) << (13);
/// <summary>
/// ALG_TYPE_BLOCK.
/// </summary>
public const int ALG_TYPE_BLOCK = (3) << (9);
/// <summary>
/// ALG_SID_AES_256 -> 16.
/// </summary>
public const int ALG_SID_AES_256 = 16;
/// CALG_AES_128 -> (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES_128)
public const int CALG_AES_128 = (ALG_CLASS_DATA_ENCRYPT
| (ALG_TYPE_BLOCK | ALG_SID_AES_128));
/// ALG_SID_AES_128 -> 14
public const int ALG_SID_AES_128 = 14;
#endregion Constants
}
/// <summary>
/// Defines a custom exception which is thrown when
/// a native CAPI call results in an error.
/// </summary>
/// <remarks>This exception is currently internal as it's not
/// surfaced to the user. However, if we decide to surface errors
/// to the user when something fails on the remote end, then this
/// can be turned public</remarks>
[SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")]
[Serializable]
internal class PSCryptoException : Exception
{
#region Private Members
private uint _errorCode;
#endregion Private Members
#region Internal Properties
/// <summary>
/// Error code returned by the native CAPI call.
/// </summary>
internal uint ErrorCode
{
get
{
return _errorCode;
}
}
#endregion Internal Properties
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
public PSCryptoException() : this(0, new StringBuilder(string.Empty)) { }
/// <summary>
/// Constructor that will be used from within CryptoUtils.
/// </summary>
/// <param name="errorCode">error code returned by native
/// crypto application</param>
/// <param name="message">Error message associated with this failure.</param>
public PSCryptoException(uint errorCode, StringBuilder message)
: base(message.ToString())
{
_errorCode = errorCode;
}
/// <summary>
/// Constructor with just message but no inner exception.
/// </summary>
/// <param name="message">Error message associated with this failure.</param>
public PSCryptoException(string message) : this(message, null) { }
/// <summary>
/// Constructor with inner exception.
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="innerException">Inner exception.</param>
/// <remarks>This constructor is currently not called
/// explicitly from crypto utils</remarks>
public PSCryptoException(string message, Exception innerException) :
base(message, innerException)
{
_errorCode = unchecked((uint)-1);
}
/// <summary>
/// Constructor which has type specific serialization logic.
/// </summary>
/// <param name="info">Serialization info.</param>
/// <param name="context">Context in which this constructor is called.</param>
/// <remarks>Currently no custom type-specific serialization logic is
/// implemented</remarks>
protected PSCryptoException(SerializationInfo info, StreamingContext context)
:
base(info, context)
{
_errorCode = unchecked(0xFFFFFFF);
Dbg.Assert(false, "type-specific serialization logic not implemented and so this constructor should not be called");
}
#endregion Constructors
#region ISerializable Overrides
/// <summary>
/// Returns base implementation.
/// </summary>
/// <param name="info">Serialization info.</param>
/// <param name="context">Context.</param>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
#endregion ISerializable Overrides
}
/// <summary>
/// One of the issues with RSACryptoServiceProvider is that it never uses CRYPT_VERIFYCONTEXT
/// to create ephemeral keys. This class is a facade written on top of native CAPI APIs
/// to create ephemeral keys.
/// </summary>
internal class PSRSACryptoServiceProvider : IDisposable
{
#region Private Members
private PSSafeCryptProvHandle _hProv;
// handle to the provider
private bool _canEncrypt = false; // this flag indicates that this class has a key
// imported from the remote end and so can be
// used for encryption
private PSSafeCryptKey _hRSAKey;
// handle to the RSA key with which the session
// key is exchange. This can either be generated
// or imported
private PSSafeCryptKey _hSessionKey;
// handle to the session key. This can either
// be generated or imported
private bool _sessionKeyGenerated = false;
// bool indicating if session key was generated before
private static PSSafeCryptProvHandle s_hStaticProv;
private static PSSafeCryptKey s_hStaticRSAKey;
private static bool s_keyPairGenerated = false;
private static object s_syncObject = new object();
#endregion Private Members
#region Constructors
/// <summary>
/// Private constructor.
/// </summary>
/// <param name="serverMode">indicates if this service
/// provider is operating in server mode</param>
private PSRSACryptoServiceProvider(bool serverMode)
{
if (serverMode)
{
_hProv = new PSSafeCryptProvHandle();
// We need PROV_RSA_AES to support AES-256 symmetric key
// encryption. PROV_RSA_FULL supports only RC2 and RC4
bool ret = PSCryptoNativeUtils.CryptAcquireContext(ref _hProv,
null,
null,
PSCryptoNativeUtils.PROV_RSA_AES,
PSCryptoNativeUtils.CRYPT_VERIFYCONTEXT);
CheckStatus(ret);
_hRSAKey = new PSSafeCryptKey();
}
_hSessionKey = new PSSafeCryptKey();
}
#endregion Constructors
#region Internal Methods
/// <summary>
/// Get the public key as a base64 encoded string.
/// </summary>
/// <returns>Public key as base64 encoded string.</returns>
internal string GetPublicKeyAsBase64EncodedString()
{
uint publicKeyLength = 0;
// Get key length first
bool ret = PSCryptoNativeUtils.CryptExportKey(_hRSAKey,
PSSafeCryptKey.Zero,
PSCryptoNativeUtils.PUBLICKEYBLOB,
0,
null,
ref publicKeyLength);
CheckStatus(ret);
// Create enough buffer and get the actual data
byte[] publicKey = new byte[publicKeyLength];
ret = PSCryptoNativeUtils.CryptExportKey(_hRSAKey,
PSSafeCryptKey.Zero,
PSCryptoNativeUtils.PUBLICKEYBLOB,
0,
publicKey,
ref publicKeyLength);
CheckStatus(ret);
// Convert the public key into base64 encoding so that it can be exported to
// the other end.
string result = Convert.ToBase64String(publicKey);
return result;
}
/// <summary>
/// Generates an AEX-256 session key if one is not already generated.
/// </summary>
internal void GenerateSessionKey()
{
if (_sessionKeyGenerated)
return;
lock (s_syncObject)
{
if (!_sessionKeyGenerated)
{
bool ret = PSCryptoNativeUtils.CryptGenKey(_hProv,
PSCryptoNativeUtils.CALG_AES_256,
0x01000000 | // key length = 256 bits
PSCryptoNativeUtils.CRYPT_EXPORTABLE |
PSCryptoNativeUtils.CRYPT_CREATE_SALT,
ref _hSessionKey);
CheckStatus(ret);
_sessionKeyGenerated = true;
_canEncrypt = true; // we can encrypt and decrypt once session key is available
}
}
}
/// <summary>
/// 1. Generate a AES-256 session key
/// 2. Encrypt the session key with the Imported
/// RSA public key
/// 3. Encode result above as base 64 string and export.
/// </summary>
/// <returns>Session key encrypted with receivers public key
/// and encoded as a base 64 string.</returns>
internal string SafeExportSessionKey()
{
// generate one if not already done.
GenerateSessionKey();
uint length = 0;
// get key length first
bool ret = PSCryptoNativeUtils.CryptExportKey(_hSessionKey,
_hRSAKey,
PSCryptoNativeUtils.SIMPLEBLOB,
0,
null,
ref length);
CheckStatus(ret);
// allocate buffer and export the key
byte[] sessionkey = new byte[length];
ret = PSCryptoNativeUtils.CryptExportKey(_hSessionKey,
_hRSAKey,
PSCryptoNativeUtils.SIMPLEBLOB,
0,
sessionkey,
ref length);
CheckStatus(ret);
// now we can encrypt as we have the session key
_canEncrypt = true;
// convert the key to base64 before exporting
return Convert.ToBase64String(sessionkey);
}
/// <summary>
/// Import a public key into the provider whose context
/// has been obtained.
/// </summary>
/// <param name="publicKey">Base64 encoded public key to import.</param>
internal void ImportPublicKeyFromBase64EncodedString(string publicKey)
{
Dbg.Assert(!string.IsNullOrEmpty(publicKey), "key cannot be null or empty");
byte[] convertedBase64 = Convert.FromBase64String(publicKey);
bool ret = PSCryptoNativeUtils.CryptImportKey(_hProv,
convertedBase64,
convertedBase64.Length,
PSSafeCryptKey.Zero,
0,
ref _hRSAKey);
CheckStatus(ret);
}
/// <summary>
/// Import a session key from the remote side into
/// the current CSP.
/// </summary>
/// <param name="sessionKey">encrypted session key as a
/// base64 encoded string</param>
internal void ImportSessionKeyFromBase64EncodedString(string sessionKey)
{
Dbg.Assert(!string.IsNullOrEmpty(sessionKey), "key cannot be null or empty");
byte[] convertedBase64 = Convert.FromBase64String(sessionKey);
bool ret = PSCryptoNativeUtils.CryptImportKey(_hProv,
convertedBase64,
convertedBase64.Length,
_hRSAKey,
0,
ref _hSessionKey);
CheckStatus(ret);
// now we have imported the key and will be able to
// encrypt using the session key
_canEncrypt = true;
}
/// <summary>
/// Encrypt the specified byte array.
/// </summary>
/// <param name="data">Data to encrypt.</param>
/// <returns>Encrypted byte array.</returns>
internal byte[] EncryptWithSessionKey(byte[] data)
{
// first make a copy of the original data.This is needed
// as CryptEncrypt uses the same buffer to write the encrypted data
// into.
Dbg.Assert(_canEncrypt, "Remote key has not been imported to encrypt");
byte[] encryptedData = new byte[data.Length];
Array.Copy(data, 0, encryptedData, 0, data.Length);
int dataLength = encryptedData.Length;
// encryption always happens using the session key
bool ret = PSCryptoNativeUtils.CryptEncrypt(_hSessionKey,
IntPtr.Zero,
true,
0,
encryptedData,
ref dataLength,
data.Length);
// if encryption failed, then dataLength will contain the length
// of buffer needed to store the encrypted contents. Recreate
// the buffer
if (false == ret)
{
// before reallocating the encryptedData buffer,
// zero out its contents
for (int i = 0; i < encryptedData.Length; i++)
{
encryptedData[i] = 0;
}
encryptedData = new byte[dataLength];
Array.Copy(data, 0, encryptedData, 0, data.Length);
dataLength = data.Length;
ret = PSCryptoNativeUtils.CryptEncrypt(_hSessionKey,
IntPtr.Zero,
true,
0,
encryptedData,
ref dataLength,
encryptedData.Length);
CheckStatus(ret);
}
// make sure we copy only appropriate data
// dataLength will contain the length of the encrypted
// data buffer
byte[] result = new byte[dataLength];
Array.Copy(encryptedData, 0, result, 0, dataLength);
return result;
}
/// <summary>
/// Decrypt the specified buffer.
/// </summary>
/// <param name="data">Data to decrypt.</param>
/// <returns>Decrypted buffer.</returns>
internal byte[] DecryptWithSessionKey(byte[] data)
{
// first make a copy of the original data.This is needed
// as CryptDecrypt uses the same buffer to write the decrypted data
// into.
byte[] decryptedData = new byte[data.Length];
Array.Copy(data, 0, decryptedData, 0, data.Length);
int dataLength = decryptedData.Length;
bool ret = PSCryptoNativeUtils.CryptDecrypt(_hSessionKey,
IntPtr.Zero,
true,
0,
decryptedData,
ref dataLength);
// if decryption failed, then dataLength will contain the length
// of buffer needed to store the decrypted contents. Recreate
// the buffer
if (false == ret)
{
decryptedData = new byte[dataLength];
Array.Copy(data, 0, decryptedData, 0, data.Length);
ret = PSCryptoNativeUtils.CryptDecrypt(_hSessionKey,
IntPtr.Zero,
true,
0,
decryptedData,
ref dataLength);
CheckStatus(ret);
}
// make sure we copy only appropriate data
// dataLength will contain the length of the encrypted
// data buffer
byte[] result = new byte[dataLength];
Array.Copy(decryptedData, 0, result, 0, dataLength);
// zero out the decryptedData buffer
for (int i = 0; i < decryptedData.Length; i++)
{
decryptedData[i] = 0;
}
return result;
}
/// <summary>
/// Generates key pair in a thread safe manner
/// the first time when required.
/// </summary>
internal void GenerateKeyPair()
{
if (!s_keyPairGenerated)
{
lock (s_syncObject)
{
if (!s_keyPairGenerated)
{
s_hStaticProv = new PSSafeCryptProvHandle();
// We need PROV_RSA_AES to support AES-256 symmetric key
// encryption. PROV_RSA_FULL supports only RC2 and RC4
bool ret = PSCryptoNativeUtils.CryptAcquireContext(ref s_hStaticProv,
null,
null,
PSCryptoNativeUtils.PROV_RSA_AES,
PSCryptoNativeUtils.CRYPT_VERIFYCONTEXT);
CheckStatus(ret);
s_hStaticRSAKey = new PSSafeCryptKey();
ret = PSCryptoNativeUtils.CryptGenKey(s_hStaticProv,
PSCryptoNativeUtils.AT_KEYEXCHANGE,
0x08000000 | PSCryptoNativeUtils.CRYPT_EXPORTABLE, // key length -> 2048
ref s_hStaticRSAKey);
CheckStatus(ret);
// key needs to be generated once
s_keyPairGenerated = true;
}
}
}
_hProv = s_hStaticProv;
_hRSAKey = s_hStaticRSAKey;
}
/// <summary>
/// Indicates if a key exchange is complete
/// and this provider can encrypt.
/// </summary>
internal bool CanEncrypt
{
get
{
return _canEncrypt;
}
set
{
_canEncrypt = value;
}
}
#endregion Internal Methods
#region Internal Static Methods
/// <summary>
/// Returns a crypto service provider for use in the
/// client. This will reuse the key that has been
/// generated.
/// </summary>
/// <returns>Crypto service provider for
/// the client side.</returns>
internal static PSRSACryptoServiceProvider GetRSACryptoServiceProviderForClient()
{
PSRSACryptoServiceProvider cryptoProvider = new PSRSACryptoServiceProvider(false);
// set the handles for provider and rsa key
cryptoProvider._hProv = s_hStaticProv;
cryptoProvider._hRSAKey = s_hStaticRSAKey;
return cryptoProvider;
}
/// <summary>
/// Returns a crypto service provider for use in the
/// server. This will not generate a key pair.
/// </summary>
/// <returns>Crypto service provider for
/// the server side.</returns>
internal static PSRSACryptoServiceProvider GetRSACryptoServiceProviderForServer()
{
PSRSACryptoServiceProvider cryptoProvider = new PSRSACryptoServiceProvider(true);
return cryptoProvider;
}
#endregion Internal Static Methods
#region Private Methods
/// <summary>
/// Checks the status of a call, if it had resulted in an error
/// then obtains the last error, wraps it in an exception and
/// throws the same.
/// </summary>
/// <param name="value">Value to examine.</param>
private void CheckStatus(bool value)
{
if (value)
{
return;
}
uint errorCode = PSCryptoNativeUtils.GetLastError();
StringBuilder errorMessage = new StringBuilder(new ComponentModel.Win32Exception(unchecked((int)errorCode)).Message);
throw new PSCryptoException(errorCode, errorMessage);
}
#endregion Private Methods
#region IDisposable
/// <summary>
/// Dispose resources.
/// </summary>
public void Dispose()
{
Dispose(true);
System.GC.SuppressFinalize(this);
}
// [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)]
protected void Dispose(bool disposing)
{
if (disposing)
{