-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
SymmetricAlgorithm.cs
1646 lines (1521 loc) · 76.1 KB
/
SymmetricAlgorithm.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics.CodeAnalysis;
using Internal.Cryptography;
namespace System.Security.Cryptography
{
public abstract class SymmetricAlgorithm : IDisposable
{
protected SymmetricAlgorithm()
{
ModeValue = CipherMode.CBC;
PaddingValue = PaddingMode.PKCS7;
}
[Obsolete(Obsoletions.DefaultCryptoAlgorithmsMessage, DiagnosticId = Obsoletions.DefaultCryptoAlgorithmsDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
public static SymmetricAlgorithm Create() =>
throw new PlatformNotSupportedException(SR.Cryptography_DefaultAlgorithm_NotSupported);
[Obsolete(Obsoletions.CryptoStringFactoryMessage, DiagnosticId = Obsoletions.CryptoStringFactoryDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[RequiresUnreferencedCode(CryptoConfigForwarder.CreateFromNameUnreferencedCodeMessage)]
public static SymmetricAlgorithm? Create(string algName) =>
CryptoConfigForwarder.CreateFromName<SymmetricAlgorithm>(algName);
public virtual int FeedbackSize
{
get
{
return FeedbackSizeValue;
}
set
{
if (value <= 0 || value > BlockSizeValue || (value % 8) != 0)
throw new CryptographicException(SR.Cryptography_InvalidFeedbackSize);
FeedbackSizeValue = value;
}
}
public virtual int BlockSize
{
get
{
return BlockSizeValue;
}
set
{
bool validatedByZeroSkipSizeKeySizes;
if (!value.IsLegalSize(this.LegalBlockSizes, out validatedByZeroSkipSizeKeySizes))
throw new CryptographicException(SR.Cryptography_InvalidBlockSize);
if (BlockSizeValue == value && !validatedByZeroSkipSizeKeySizes) // The !validatedByZeroSkipSizeKeySizes check preserves a very obscure back-compat behavior.
return;
BlockSizeValue = value;
IVValue = null;
return;
}
}
public virtual byte[] IV
{
get
{
if (IVValue == null)
GenerateIV();
return IVValue.CloneByteArray()!;
}
set
{
ArgumentNullException.ThrowIfNull(value);
if (value.Length != this.BlockSize / 8)
throw new CryptographicException(SR.Cryptography_InvalidIVSize);
IVValue = value.CloneByteArray();
}
}
public virtual byte[] Key
{
get
{
if (KeyValue == null)
GenerateKey();
return KeyValue.CloneByteArray()!;
}
set
{
ArgumentNullException.ThrowIfNull(value);
long bitLength = value.Length * 8L;
if (bitLength > int.MaxValue || !ValidKeySize((int)bitLength))
throw new CryptographicException(SR.Cryptography_InvalidKeySize);
// must convert bytes to bits
this.KeySize = (int)bitLength;
KeyValue = value.CloneByteArray();
}
}
public virtual int KeySize
{
get
{
return KeySizeValue;
}
set
{
if (!ValidKeySize(value))
throw new CryptographicException(SR.Cryptography_InvalidKeySize);
KeySizeValue = value;
KeyValue = null;
}
}
public virtual KeySizes[] LegalBlockSizes
{
get
{
// .NET Framework compat: No null check is performed.
return (KeySizes[])LegalBlockSizesValue!.Clone();
}
}
public virtual KeySizes[] LegalKeySizes
{
get
{
// .NET Framework compat: No null check is performed.
return (KeySizes[])LegalKeySizesValue!.Clone();
}
}
public virtual CipherMode Mode
{
get
{
return ModeValue;
}
set
{
if (!(value == CipherMode.CBC || value == CipherMode.ECB || value == CipherMode.CFB))
throw new CryptographicException(SR.Cryptography_InvalidCipherMode);
ModeValue = value;
}
}
public virtual PaddingMode Padding
{
get
{
return PaddingValue;
}
set
{
if ((value < PaddingMode.None) || (value > PaddingMode.ISO10126))
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
PaddingValue = value;
}
}
public virtual ICryptoTransform CreateDecryptor()
{
return CreateDecryptor(Key, IV);
}
public abstract ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV);
public virtual ICryptoTransform CreateEncryptor()
{
return CreateEncryptor(Key, IV);
}
public abstract ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV);
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Clear()
{
(this as IDisposable).Dispose();
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (KeyValue != null)
{
Array.Clear(KeyValue);
KeyValue = null;
}
if (IVValue != null)
{
Array.Clear(IVValue);
IVValue = null;
}
}
}
public abstract void GenerateIV();
public abstract void GenerateKey();
public bool ValidKeySize(int bitLength)
{
KeySizes[] validSizes = this.LegalKeySizes;
if (validSizes == null)
return false;
return bitLength.IsLegalSize(validSizes);
}
/// <summary>
/// Gets the length of a ciphertext with a given padding mode and plaintext length in ECB mode.
/// </summary>
/// <param name="paddingMode">The padding mode used to pad the plaintext to the algorithm's block size.</param>
/// <param name="plaintextLength">The plaintext length, in bytes.</param>
/// <returns>The length, in bytes, of the ciphertext with padding.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <para>
/// <paramref name="plaintextLength" /> is a negative number.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="plaintextLength" /> when padded is too large to represent as
/// a signed 32-bit integer.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </para>
/// </exception>
/// <exception cref="CryptographicException">
/// <para>
/// <see cref="BlockSize" /> is not a positive integer.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <see cref="BlockSize" /> is not a whole number of bytes. It must be divisible by 8.
/// </para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// The padding mode <see cref="PaddingMode.None" /> was used, but <paramref name="plaintextLength" />
/// is not a whole number of blocks.
/// </para>
/// </exception>
public int GetCiphertextLengthEcb(int plaintextLength, PaddingMode paddingMode) =>
GetCiphertextLengthBlockAligned(plaintextLength, paddingMode);
/// <summary>
/// Gets the length of a ciphertext with a given padding mode and plaintext length in CBC mode.
/// </summary>
/// <param name="paddingMode">The padding mode used to pad the plaintext to the algorithm's block size.</param>
/// <param name="plaintextLength">The plaintext length, in bytes.</param>
/// <returns>The length, in bytes, of the ciphertext with padding.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <para>
/// <paramref name="plaintextLength" /> is a negative number.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="plaintextLength" /> when padded is too large to represent as
/// a signed 32-bit integer.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </para>
/// </exception>
/// <exception cref="CryptographicException">
/// <para>
/// <see cref="BlockSize" /> is not a positive integer.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <see cref="BlockSize" /> is not a whole number of bytes. It must be divisible by 8.
/// </para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// The padding mode <see cref="PaddingMode.None" /> was used, but <paramref name="plaintextLength" />
/// is not a whole number of blocks.
/// </para>
/// </exception>
public int GetCiphertextLengthCbc(int plaintextLength, PaddingMode paddingMode = PaddingMode.PKCS7) =>
GetCiphertextLengthBlockAligned(plaintextLength, paddingMode);
private int GetCiphertextLengthBlockAligned(int plaintextLength, PaddingMode paddingMode)
{
ArgumentOutOfRangeException.ThrowIfNegative(plaintextLength);
int blockSizeBits = BlockSize; // The BlockSize property is in bits.
if (blockSizeBits <= 0 || (blockSizeBits & 0b111) != 0)
throw new InvalidOperationException(SR.InvalidOperation_UnsupportedBlockSize);
int blockSizeBytes = blockSizeBits >> 3;
int wholeBlocks = Math.DivRem(plaintextLength, blockSizeBytes, out int remainder) * blockSizeBytes;
switch (paddingMode)
{
case PaddingMode.None when remainder != 0:
throw new ArgumentException(SR.Cryptography_MatchBlockSize, nameof(plaintextLength));
case PaddingMode.None:
case PaddingMode.Zeros when remainder == 0:
return plaintextLength;
case PaddingMode.Zeros:
case PaddingMode.PKCS7:
case PaddingMode.ANSIX923:
case PaddingMode.ISO10126:
if (int.MaxValue - wholeBlocks < blockSizeBytes)
{
throw new ArgumentOutOfRangeException(nameof(plaintextLength), SR.Cryptography_PlaintextTooLarge);
}
return wholeBlocks + blockSizeBytes;
default:
throw new ArgumentOutOfRangeException(nameof(paddingMode), SR.Cryptography_InvalidPaddingMode);
}
}
/// <summary>
/// Gets the length of a ciphertext with a given padding mode and plaintext length in CFB mode.
/// </summary>
/// <param name="paddingMode">The padding mode used to pad the plaintext to the feedback size.</param>
/// <param name="plaintextLength">The plaintext length, in bytes.</param>
/// <param name="feedbackSizeInBits">The feedback size, in bits.</param>
/// <returns>The length, in bytes, of the ciphertext with padding.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <para>
/// <paramref name="feedbackSizeInBits" /> is not a positive number.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="plaintextLength" /> is a negative number.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="plaintextLength" /> when padded is too large to represent as
/// a signed 32-bit integer.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// The padding mode <see cref="PaddingMode.None" /> was used, but <paramref name="plaintextLength" />
/// is not a whole number of blocks.
/// </para>
/// <para>
/// - or -
/// </para>
/// <para>
/// <paramref name="feedbackSizeInBits" /> is not a whole number of bytes. It must be divisible by 8.
/// </para>
/// </exception>
/// <remarks>
/// <paramref name="feedbackSizeInBits" /> accepts any value that is a valid feedback size, regardless if the algorithm
/// supports the specified feedback size.
/// </remarks>
public int GetCiphertextLengthCfb(int plaintextLength, PaddingMode paddingMode = PaddingMode.None, int feedbackSizeInBits = 8)
{
ArgumentOutOfRangeException.ThrowIfNegative(plaintextLength);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(feedbackSizeInBits);
if ((feedbackSizeInBits & 0b111) != 0)
throw new ArgumentException(SR.Argument_BitsMustBeWholeBytes, nameof(feedbackSizeInBits));
int feedbackSizeInBytes = feedbackSizeInBits >> 3;
int feedbackAligned = Math.DivRem(plaintextLength, feedbackSizeInBytes, out int remainder) * feedbackSizeInBytes;
switch (paddingMode)
{
case PaddingMode.None when remainder != 0:
throw new ArgumentException(SR.Cryptography_MatchFeedbackSize, nameof(plaintextLength));
case PaddingMode.None:
case PaddingMode.Zeros when remainder == 0:
return plaintextLength;
case PaddingMode.Zeros:
case PaddingMode.PKCS7:
case PaddingMode.ANSIX923:
case PaddingMode.ISO10126:
if (int.MaxValue - feedbackAligned < feedbackSizeInBytes)
{
throw new ArgumentOutOfRangeException(nameof(plaintextLength), SR.Cryptography_PlaintextTooLarge);
}
return feedbackAligned + feedbackSizeInBytes;
default:
throw new ArgumentOutOfRangeException(nameof(paddingMode), SR.Cryptography_InvalidPaddingMode);
}
}
/// <summary>
/// Decrypts data using ECB mode with the specified padding mode.
/// </summary>
/// <param name="ciphertext">The data to decrypt.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <returns>The decrypted plaintext data.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="ciphertext" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="CryptographicException">
/// The ciphertext could not be decrypted successfully.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryDecryptEcbCore" />.
/// </remarks>
public byte[] DecryptEcb(byte[] ciphertext, PaddingMode paddingMode)
{
ArgumentNullException.ThrowIfNull(ciphertext);
// Padding mode is validated by callee.
return DecryptEcb(new ReadOnlySpan<byte>(ciphertext), paddingMode);
}
/// <summary>
/// Decrypts data using ECB mode with the specified padding mode.
/// </summary>
/// <param name="ciphertext">The data to decrypt.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <returns>The decrypted plaintext data.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="CryptographicException">
/// The ciphertext could not be decrypted successfully.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryDecryptEcbCore" />.
/// </remarks>
public byte[] DecryptEcb(ReadOnlySpan<byte> ciphertext, PaddingMode paddingMode)
{
CheckPaddingMode(paddingMode);
// This could get returned directly to the caller if we there was no padding
// that needed to get removed, so don't rent from a pool.
byte[] decryptBuffer = GC.AllocateUninitializedArray<byte>(ciphertext.Length);
if (!TryDecryptEcbCore(ciphertext, decryptBuffer, paddingMode, out int written)
|| (uint)written > decryptBuffer.Length)
{
// This means decrypting the ciphertext grew in to a larger plaintext or overflowed.
// A user-derived class could do this, but it is not expected in any of the
// implementations that we ship.
throw new CryptographicException(SR.Argument_DestinationTooShort);
}
// Array.Resize will no-op if the array does not need to be resized.
Array.Resize(ref decryptBuffer, written);
return decryptBuffer;
}
/// <summary>
/// Decrypts data into the specified buffer, using ECB mode with the specified padding mode.
/// </summary>
/// <param name="ciphertext">The data to decrypt.</param>
/// <param name="destination">The buffer to receive the plaintext data.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <returns>The total number of bytes written to <paramref name="destination" /></returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="CryptographicException">
/// The ciphertext could not be decrypted successfully.
/// </exception>
/// <exception cref="ArgumentException">
/// The buffer in <paramref name="destination"/> is too small to hold the plaintext data.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryDecryptEcbCore" />.
/// </remarks>
public int DecryptEcb(ReadOnlySpan<byte> ciphertext, Span<byte> destination, PaddingMode paddingMode)
{
CheckPaddingMode(paddingMode);
if (!TryDecryptEcbCore(ciphertext, destination, paddingMode, out int written))
{
throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination));
}
return written;
}
/// <summary>
/// Attempts to decrypt data into the specified buffer, using ECB mode with the specified padding mode.
/// </summary>
/// <param name="ciphertext">The data to decrypt.</param>
/// <param name="destination">The buffer to receive the plaintext data.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <param name="bytesWritten">When this method returns, the total number of bytes written to <paramref name="destination" />.</param>
/// <returns><see langword="true"/> if <paramref name="destination"/> was large enough to receive the decrypted data; otherwise, <see langword="false" />.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="CryptographicException">
/// The ciphertext could not be decrypted successfully.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryDecryptEcbCore" />.
/// </remarks>
public bool TryDecryptEcb(ReadOnlySpan<byte> ciphertext, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten)
{
CheckPaddingMode(paddingMode);
return TryDecryptEcbCore(ciphertext, destination, paddingMode, out bytesWritten);
}
/// <summary>
/// Encrypts data using ECB mode with the specified padding mode.
/// </summary>
/// <param name="plaintext">The data to encrypt.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <returns>The encrypted ciphertext data.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="plaintext" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="CryptographicException">
/// The plaintext could not be encrypted successfully.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryEncryptEcbCore" />.
/// </remarks>
public byte[] EncryptEcb(byte[] plaintext, PaddingMode paddingMode)
{
ArgumentNullException.ThrowIfNull(plaintext);
// paddingMode is validated by callee
return EncryptEcb(new ReadOnlySpan<byte>(plaintext), paddingMode);
}
/// <summary>
/// Encrypts data using ECB mode with the specified padding mode.
/// </summary>
/// <param name="plaintext">The data to encrypt.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <returns>The encrypted ciphertext data.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="CryptographicException">
/// The plaintext could not be encrypted successfully.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryEncryptEcbCore" />.
/// </remarks>
public byte[] EncryptEcb(ReadOnlySpan<byte> plaintext, PaddingMode paddingMode)
{
CheckPaddingMode(paddingMode);
int ciphertextLength = GetCiphertextLengthEcb(plaintext.Length, paddingMode);
// We expect most if not all uses to encrypt to exactly the ciphertextLength
byte[] buffer = GC.AllocateUninitializedArray<byte>(ciphertextLength);
if (!TryEncryptEcbCore(plaintext, buffer, paddingMode, out int written) ||
written != ciphertextLength)
{
// This means a user-derived implementation added more padding than we expected or
// did something non-standard (encrypt to a partial block). This can't happen for
// multiple padding blocks since the buffer would have been too small in the first
// place. It doesn't make sense to try and support partial block encryption, likely
// something went very wrong. So throw.
throw new CryptographicException(SR.Format(SR.Cryptography_EncryptedIncorrectLength, nameof(TryEncryptEcbCore)));
}
return buffer;
}
/// <summary>
/// Encrypts data into the specified buffer, using ECB mode with the specified padding mode.
/// </summary>
/// <param name="plaintext">The data to encrypt.</param>
/// <param name="destination">The buffer to receive the ciphertext data.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <returns>The total number of bytes written to <paramref name="destination" />.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="CryptographicException">
/// The plaintext could not be encrypted successfully.
/// </exception>
/// <exception cref="ArgumentException">
/// The buffer in <paramref name="destination"/> is too small to hold the ciphertext data.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryEncryptEcbCore" />.
/// </remarks>
public int EncryptEcb(ReadOnlySpan<byte> plaintext, Span<byte> destination, PaddingMode paddingMode)
{
CheckPaddingMode(paddingMode);
if (!TryEncryptEcbCore(plaintext, destination, paddingMode, out int written))
{
throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination));
}
return written;
}
/// <summary>
/// Attempts to encrypt data into the specified buffer, using ECB mode with the specified padding mode.
/// </summary>
/// <param name="plaintext">The data to encrypt.</param>
/// <param name="destination">The buffer to receive the ciphertext data.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <param name="bytesWritten">When this method returns, the total number of bytes written to <paramref name="destination" />.</param>
/// <returns><see langword="true"/> if <paramref name="destination"/> was large enough to receive the encrypted data; otherwise, <see langword="false" />.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="CryptographicException">
/// The plaintext could not be encrypted successfully.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryEncryptEcbCore" />.
/// </remarks>
public bool TryEncryptEcb(ReadOnlySpan<byte> plaintext, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten)
{
CheckPaddingMode(paddingMode);
return TryEncryptEcbCore(plaintext, destination, paddingMode, out bytesWritten);
}
/// <summary>
/// Decrypts data using CBC mode with the specified padding mode.
/// </summary>
/// <param name="ciphertext">The data to decrypt.</param>
/// <param name="iv">The initialization vector.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <returns>The decrypted plaintext data.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="ciphertext" /> or <paramref name="iv" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="iv" /> is the incorrect length. Callers are expected to pass an initialization vector
/// that is exactly <see cref="BlockSize" /> in length, converted to bytes (<c>BlockSize / 8</c>).
/// </exception>
/// <exception cref="CryptographicException">
/// The ciphertext could not be decrypted successfully.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryDecryptCbcCore" />.
/// </remarks>
public byte[] DecryptCbc(byte[] ciphertext, byte[] iv, PaddingMode paddingMode = PaddingMode.PKCS7)
{
ArgumentNullException.ThrowIfNull(ciphertext);
ArgumentNullException.ThrowIfNull(iv);
return DecryptCbc(new ReadOnlySpan<byte>(ciphertext), new ReadOnlySpan<byte>(iv), paddingMode);
}
/// <summary>
/// Decrypts data using CBC mode with the specified padding mode.
/// </summary>
/// <param name="ciphertext">The data to decrypt.</param>
/// <param name="iv">The initialization vector.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <returns>The decrypted plaintext data.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="iv" /> is the incorrect length. Callers are expected to pass an initialization vector
/// that is exactly <see cref="BlockSize" /> in length, converted to bytes (<c>BlockSize / 8</c>).
/// </exception>
/// <exception cref="CryptographicException">
/// The ciphertext could not be decrypted successfully.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryDecryptCbcCore" />.
/// </remarks>
public byte[] DecryptCbc(ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> iv, PaddingMode paddingMode = PaddingMode.PKCS7)
{
CheckPaddingMode(paddingMode);
CheckInitializationVectorSize(iv);
// CBC is more typically used with padding so the resulting plaintext is
// unlikely to be the same size as the ciphertext. So we rent since we are
// likely to going to need to resize anyway.
// This will pass the rented buffer to user code (the virtual Core) so
// don't use CryptoPool.
byte[] decryptRent = ArrayPool<byte>.Shared.Rent(ciphertext.Length);
Span<byte> decryptBuffer = decryptRent.AsSpan(0, ciphertext.Length);
if (!TryDecryptCbcCore(ciphertext, iv, decryptBuffer, paddingMode, out int written)
|| (uint)written > decryptBuffer.Length)
{
// This means decrypting the ciphertext grew in to a larger plaintext or overflowed.
// A user-derived class could do this, but it is not expected in any of the
// implementations that we ship.
throw new CryptographicException(SR.Argument_DestinationTooShort);
}
byte[] plaintext = decryptBuffer.Slice(0, written).ToArray();
CryptographicOperations.ZeroMemory(decryptBuffer.Slice(0, written));
ArrayPool<byte>.Shared.Return(decryptRent);
return plaintext;
}
/// <summary>
/// Decrypts data into the specified buffer, using CBC mode with the specified padding mode.
/// </summary>
/// <param name="ciphertext">The data to decrypt.</param>
/// <param name="iv">The initialization vector.</param>
/// <param name="destination">The buffer to receive the plaintext data.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <returns>The total number of bytes written to <paramref name="destination" /></returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="iv" /> is the incorrect length. Callers are expected to pass an initialization vector
/// that is exactly <see cref="BlockSize" /> in length, converted to bytes (<c>BlockSize / 8</c>).
/// </exception>
/// <exception cref="CryptographicException">
/// The ciphertext could not be decrypted successfully.
/// </exception>
/// <exception cref="ArgumentException">
/// The buffer in <paramref name="destination"/> is too small to hold the plaintext data.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryDecryptCbcCore" />.
/// </remarks>
public int DecryptCbc(
ReadOnlySpan<byte> ciphertext,
ReadOnlySpan<byte> iv,
Span<byte> destination,
PaddingMode paddingMode = PaddingMode.PKCS7)
{
CheckPaddingMode(paddingMode);
CheckInitializationVectorSize(iv);
if (!TryDecryptCbcCore(ciphertext, iv, destination, paddingMode, out int written))
{
throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination));
}
return written;
}
/// <summary>
/// Attempts to decrypt data into the specified buffer, using CBC mode with the specified padding mode.
/// </summary>
/// <param name="ciphertext">The data to decrypt.</param>
/// <param name="iv">The initialization vector.</param>
/// <param name="destination">The buffer to receive the plaintext data.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <param name="bytesWritten">When this method returns, the total number of bytes written to <paramref name="destination" />.</param>
/// <returns><see langword="true"/> if <paramref name="destination"/> was large enough to receive the decrypted data; otherwise, <see langword="false" />.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="iv" /> is the incorrect length. Callers are expected to pass an initialization vector
/// that is exactly <see cref="BlockSize" /> in length, converted to bytes (<c>BlockSize / 8</c>).
/// </exception>
/// <exception cref="CryptographicException">
/// The ciphertext could not be decrypted successfully.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryDecryptCbcCore" />.
/// </remarks>
public bool TryDecryptCbc(
ReadOnlySpan<byte> ciphertext,
ReadOnlySpan<byte> iv,
Span<byte> destination,
out int bytesWritten,
PaddingMode paddingMode = PaddingMode.PKCS7)
{
CheckPaddingMode(paddingMode);
CheckInitializationVectorSize(iv);
return TryDecryptCbcCore(ciphertext, iv, destination, paddingMode, out bytesWritten);
}
/// <summary>
/// Encrypts data using CBC mode with the specified padding mode.
/// </summary>
/// <param name="plaintext">The data to encrypt.</param>
/// <param name="iv">The initialization vector.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <returns>The encrypted ciphertext data.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="plaintext" /> or <paramref name="iv" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="iv" /> is the incorrect length. Callers are expected to pass an initialization vector
/// that is exactly <see cref="BlockSize" /> in length, converted to bytes (<c>BlockSize / 8</c>).
/// </exception>
/// <exception cref="CryptographicException">
/// The plaintext could not be encrypted successfully.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryEncryptCbcCore" />.
/// </remarks>
public byte[] EncryptCbc(byte[] plaintext, byte[] iv, PaddingMode paddingMode = PaddingMode.PKCS7)
{
ArgumentNullException.ThrowIfNull(plaintext);
ArgumentNullException.ThrowIfNull(iv);
return EncryptCbc(new ReadOnlySpan<byte>(plaintext), new ReadOnlySpan<byte>(iv), paddingMode);
}
/// <summary>
/// Encrypts data using CBC mode with the specified padding mode.
/// </summary>
/// <param name="plaintext">The data to encrypt.</param>
/// <param name="iv">The initialization vector.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <returns>The encrypted ciphertext data.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="iv" /> is the incorrect length. Callers are expected to pass an initialization vector
/// that is exactly <see cref="BlockSize" /> in length, converted to bytes (<c>BlockSize / 8</c>).
/// </exception>
/// <exception cref="CryptographicException">
/// The plaintext could not be encrypted successfully.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryEncryptCbcCore" />.
/// </remarks>
public byte[] EncryptCbc(
ReadOnlySpan<byte> plaintext,
ReadOnlySpan<byte> iv,
PaddingMode paddingMode = PaddingMode.PKCS7)
{
CheckPaddingMode(paddingMode);
CheckInitializationVectorSize(iv);
int ciphertextLength = GetCiphertextLengthCbc(plaintext.Length, paddingMode);
// We expect most if not all uses to encrypt to exactly the ciphertextLength
byte[] buffer = GC.AllocateUninitializedArray<byte>(ciphertextLength);
if (!TryEncryptCbcCore(plaintext, iv, buffer, paddingMode, out int written) ||
written != ciphertextLength)
{
// This means a user-derived implementation added more padding than we expected or
// did something non-standard (encrypt to a partial block). This can't happen for
// multiple padding blocks since the buffer would have been too small in the first
// place. It doesn't make sense to try and support partial block encryption, likely
// something went very wrong. So throw.
throw new CryptographicException(SR.Format(SR.Cryptography_EncryptedIncorrectLength, nameof(TryEncryptCbcCore)));
}
return buffer;
}
/// <summary>
/// Encrypts data into the specified buffer, using CBC mode with the specified padding mode.
/// </summary>
/// <param name="plaintext">The data to encrypt.</param>
/// <param name="iv">The initialization vector.</param>
/// <param name="destination">The buffer to receive the ciphertext data.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <returns>The total number of bytes written to <paramref name="destination" />.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="iv" /> is the incorrect length. Callers are expected to pass an initialization vector
/// that is exactly <see cref="BlockSize" /> in length, converted to bytes (<c>BlockSize / 8</c>).
/// </exception>
/// <exception cref="CryptographicException">
/// The plaintext could not be encrypted successfully.
/// </exception>
/// <exception cref="ArgumentException">
/// The buffer in <paramref name="destination"/> is too small to hold the ciphertext data.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryEncryptCbcCore" />.
/// </remarks>
public int EncryptCbc(
ReadOnlySpan<byte> plaintext,
ReadOnlySpan<byte> iv,
Span<byte> destination,
PaddingMode paddingMode = PaddingMode.PKCS7)
{
CheckPaddingMode(paddingMode);
CheckInitializationVectorSize(iv);
if (!TryEncryptCbcCore(plaintext, iv, destination, paddingMode, out int written))
{
throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination));
}
return written;
}
/// <summary>
/// Attempts to encrypt data into the specified buffer, using CBC mode with the specified padding mode.
/// </summary>
/// <param name="plaintext">The data to encrypt.</param>
/// <param name="iv">The initialization vector.</param>
/// <param name="destination">The buffer to receive the ciphertext data.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <param name="bytesWritten">When this method returns, the total number of bytes written to <paramref name="destination" />.</param>
/// <returns><see langword="true"/> if <paramref name="destination"/> was large enough to receive the encrypted data; otherwise, <see langword="false" />.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="iv" /> is the incorrect length. Callers are expected to pass an initialization vector
/// that is exactly <see cref="BlockSize" /> in length, converted to bytes (<c>BlockSize / 8</c>).
/// </exception>
/// <exception cref="CryptographicException">
/// The plaintext could not be encrypted successfully.
/// </exception>
/// <remarks>
/// This method's behavior is defined by <see cref="TryEncryptCbcCore" />.
/// </remarks>
public bool TryEncryptCbc(
ReadOnlySpan<byte> plaintext,
ReadOnlySpan<byte> iv,
Span<byte> destination,
out int bytesWritten,
PaddingMode paddingMode = PaddingMode.PKCS7)
{
CheckPaddingMode(paddingMode);
CheckInitializationVectorSize(iv);
return TryEncryptCbcCore(plaintext, iv, destination, paddingMode, out bytesWritten);
}
/// <summary>
/// Decrypts data using CFB mode with the specified padding mode and
/// feedback size.
/// </summary>
/// <param name="ciphertext">The data to decrypt.</param>
/// <param name="iv">The initialization vector.</param>
/// <param name="paddingMode">The padding mode used to produce the ciphertext and remove during decryption.</param>
/// <param name="feedbackSizeInBits">The feedback size, specified in bits.</param>
/// <returns>The decrypted plaintext data.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="ciphertext" /> or <paramref name="iv" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <para>
/// <paramref name="paddingMode" /> is not a valid padding mode.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="feedbackSizeInBits" /> is not positive or represent a whole number of bytes.
/// </para>
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="iv" /> is the incorrect length. Callers are expected to pass an initialization vector
/// that is exactly <see cref="BlockSize" /> in length, converted to bytes (<c>BlockSize / 8</c>).
/// </exception>
/// <exception cref="CryptographicException">
/// <para>
/// The ciphertext could not be decrypted successfully.