-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathDECCipherBase.pas
More file actions
1232 lines (1124 loc) · 46.4 KB
/
DECCipherBase.pas
File metadata and controls
1232 lines (1124 loc) · 46.4 KB
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
{*****************************************************************************
The DEC team (see file NOTICE.txt) licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. A copy of this licence is found in the root directory
of this project in the file LICENCE.txt or alternatively at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*****************************************************************************}
unit DECCipherBase;
{$INCLUDE DECOptions.inc}
interface
uses
{$IFDEF FPC}
SysUtils, Classes,
{$ELSE}
System.SysUtils, System.Classes, Generics.Collections,
{$ENDIF}
DECBaseClass, DECFormatBase, DECTypes;
type
/// <summary>
/// Possible kindes of cipher algorithms independent of any block
/// concatenation mode etc.
/// <para>
/// ctNull = special "do nothing cipher"
/// </para>
/// <para>
/// ctStream = cipher operating on a stream of bytes instead of blocks
/// </para>
/// <para>
/// ctBlock = cipher operating on blocks of bytes with a fixed size
/// </para>
/// <para>
/// ctSymmetric = cipher where the same key encrypts and decrypts
/// </para>
/// <para>
/// ctAsymetric = cipher where encryption and decryption requires
/// different keys
/// </para>
/// </summary>
TCipherTypes = (ctNull, ctStream, ctBlock, ctSymmetric, ctAsymmetric);
/// <summary>
/// Actual kind of cipher algorithm
/// </summary>
TCipherType = set of TCipherTypes;
/// <summary>
/// Padding used to fill the last incomplete block of a block encryption
/// algorithm. To be expanded in a future version
/// </summary>
TBlockFillMode = (fmByte);
/// <summary>
/// Record containing meta data about a certain cipher
/// </summary>
TCipherContext = packed record
/// <summary>
/// maximal key size in bytes
/// </summary>
KeySize : Integer;
/// <summary>
/// mininmal block size in bytes, e.g. 1 = Streamcipher
/// </summary>
BlockSize : Integer;
/// <summary>
/// internal buffersize in bytes
/// </summary>
BufferSize : Integer;
/// <summary>
/// Size in bytes of the FAdditionalBuffer used by some of the cipher algorithms
/// </summary>
AdditionalBufferSize : Integer;
/// <summary>
/// When true the memory a certain internal pointer (FAdditionalBuffer)
/// points to needs to be backuped during key initialization if no init
/// vector is specified and restored at the end of that init method.
/// Same in Done method as well.
/// </summary>
NeedsAdditionalBufferBackup : Boolean;
/// <summary>
/// Minimum number of rounds allowed for any block cipher having a rounds
/// property. In all other cases it will be set to 1.
/// </summary>
MinRounds : UInt16;
/// <summary>
/// Maximum number of rounds allowed for any block cipher having a rounds
/// property. In all other cases it will be set to 1.
/// </summary>
MaxRounds : UInt16;
/// <summary>
/// Specifies the kind of cipher
/// </summary>
CipherType : TCipherType;
end;
/// <summary>
/// TCipher.State represents the internal state of processing
/// <para>
/// csNew : cipher isn't initialized, .Init() must be called before en/decode
/// </para>
/// <para>
/// csInitialized : cipher is initialized by .Init(), i.e. Keysetup was processed
/// </para>
/// <para>
/// csEncode : Encoding was started, and more chunks can be encoded, but not decoded
/// </para>
/// <para>
/// csDecode : Decoding was started, and more chunks can be decoded, but not encoded
/// </para>
/// <para>
/// csPadded : trough En/Decoding the messagechunks are padded, no more chunks can
/// be processed, the cipher is blocked
/// </para>
/// <para>
/// csDone : Processing is finished and Cipher.Done was called. Now, new En/Decoding
/// can be started without calling .Init() before. csDone is basically
/// identical to csInitialized, except Cipher.Buffer holds the encrypted
/// last state of Cipher.Feedback which can be used as
/// Cipher-based message authentication code (CMAC).
/// </para>
/// </summary>
TCipherState = (csNew, csInitialized, csEncode, csDecode, csPadded, csDone);
/// <summary>
/// Set of cipher states, representing the internal state of processing
/// </summary>
TCipherStates = set of TCipherState;
/// <summary>
/// This defines how the individual blocks of the data to be processed are
/// linked with each other.
///
/// Modes cmCBCx, cmCTSx, cmCTSxx, cmCFBx, cmOFBx, cmCFSx, cmECBx are working
/// on Blocks of Cipher.BufferSize bytes, when using a Blockcipher that's equal
/// to Cipher.BlockSize.
///
/// Modes cmCFB8, cmOFB8, cmCFS8 work on 8 bit Feedback Shift Registers.
///
/// Modes cmCTSx, cmCFSx, cmCFS8 are proprietary modes developed by Hagen
/// Reddmann. These modes work like cmCBCx, cmCFBx, cmCFB8 but with double
/// XOR'ing of the inputstream into the feedback register.
///
/// Mode cmECBx needs message padding to be a multiple of Cipher.BlockSize and
/// should be used only in 1-byte Streamciphers.
///
/// Modes cmCFB8, cmCFBx, cmOFB8, cmOFBx, cmCFS8 and cmCFSx need no padding.
///
/// Modes cmCTSx, cmCBCx need no external padding, because internally the last
/// truncated block is padded by cmCFS8 or cmCFB8. After padding these Modes
/// cannot be used to process any more data. If needed to process chunks of
/// data then each chunk must be algined to Cipher.BufferSize bytes.
///
/// Mode cmCTS3 is a proprietary mode developed by Frederik Winkelsdorf. It
/// replaces the CFS8 padding of the truncated final block with a CFSx padding.
/// Useful when converting projects that previously used the old DEC v3.0. It
/// has the same restrictions for external padding and chunk processing as
/// cmCTSx has.
/// </summary>
TCipherMode = (
cmCTSx, // double CBC, with CFS8 padding of truncated final block
cmCBCx, // Cipher Block Chaining, with CFB8 padding of truncated final block
cmCFB8, // 8bit Cipher Feedback mode
cmCFBx, // CFB on Blocksize of Cipher
cmOFB8, // 8bit Output Feedback mode
cmOFBx, // OFB on Blocksize bytes
cmCFS8, // 8Bit CFS, double CFB
cmCFSx, // CFS on Blocksize bytes
cmECBx, // Electronic Code Book
cmGCM // Galois Counter Mode
{$IFDEF DEC3_CMCTS}
,cmCTS3 // double CBC, with less secure padding of truncated final block
// for DEC 3.0 compatibility only (see DECOptions.inc)
{$ENDIF DEC3_CMCTS}
);
/// <summary>
/// Each cipher algorithm has to implement a Encode and a Decode method which
/// has the same signature as this type. The CipherFormats get these
/// encode/decode methods passed to do their work.
/// </summary>
/// <param name="Source">
/// Contains the data to be encoded or decoded
/// </param>
/// <param name="Dest">
/// Contains the data after encoding or decoding
/// </param>
/// <param name="DataSize">
/// Number of bytes to encode or decode
/// </param>
TDECCipherCodeEvent = procedure(const Source; var Dest; DataSize: Integer) of object;
/// <summary>
/// Class type of the cipher base class, relevant for the class registration
/// </summary>
TDECCipherClass = class of TDECCipher;
/// <summary>
/// Base class for all implemented cipher algorithms
/// </summary>
/// <remarks>
/// When adding new block ciphers do never directly inherit from this class!
/// Inherit from TDECCipherFormats.
/// </remarks>
TDECCipher = class(TDECObject)
strict private
/// <summary>
/// This is the complete memory block containing FInitializationVector,
/// FFeedback, FBuffer and FAdditionalBuffer
/// </summary>
FData : PUInt8Array;
/// <summary>
/// This is the size of FData in byte
/// </summary>
FDataSize : Integer;
strict protected
/// <summary>
/// Padding mode used to concatenate/connect blocks in a block cipher
/// </summary>
FMode : TCipherMode;
/// <summary>
/// Mode used for filling up an incomplete last block in a block cipher
/// </summary>
FFillMode : TBlockFillMode;
/// <summary>
/// Current processing state
/// </summary>
FState: TCipherState;
/// <summary>
/// Size of the internally used processing buffer in byte
/// </summary>
FBufferSize: Integer;
/// <summary>
/// At which position of the buffer are we currently operating?
/// </summary>
FBufferIndex: Integer;
/// <summary>
/// Some algorithms, mostly the cipher mode ones, need a temporary buffer
/// to work with. Some other methods like Done or Valid cipher need to pass
/// a buffer as parameter as that is ecpected by the called method.
/// If Done was called, FBuffer contains a C-MAC which is the encryption
/// of the last block concatention feedback.
/// </summary>
FBuffer: PUInt8Array;
/// <summary>
/// Initialization vector. When using cipher modes to derive a stream
/// cipher from a block cipher algorithm some data from each encrypted block
/// is fed into the encryption of the next block. For the first block there
/// is no such encrypted data yet, so this initialization vector fills this
/// "gap".
/// </summary>
FInitializationVector: PUInt8Array;
/// <summary>
/// Size of the initialization vector in byte. Required for algorithms
/// like GCM.
/// </summary>
FInitVectorSize: Integer;
/// <summary>
/// Cipher modes are used to derive a stream cipher from block cipher
/// algorithms. For this something from the last entrypted block (or for
/// the first block from the vector) is used in the encryption of the next
/// block. It may be XORed with the next block cipher text for isntance.
/// That data "going into the next block encryption" is this feedback array
/// </summary>
FFeedback: PUInt8Array;
/// <summary>
/// Size of FAdditionalBuffer in Byte
/// </summary>
FAdditionalBufferSize: Integer;
/// <summary>
/// A buffer some of the cipher algorithms need to operate on. It is
/// some part of FBuffer like FInitializationVector and FFeedback as well.
/// </summary>
FAdditionalBuffer: Pointer;
/// <summary>
/// If a user does not specify an init vector (IV) during key setup
/// (IV length = 0) the init method generates an IV by encrypting the
/// complete memory reserved for IV. Within this memory block is the memory
/// FAdditionalBuffer points to as well, and for some algorithms this part
/// of the memory may not be altered during initialization so it is
/// backupped to this memory location and restored after the IV got encrypted.
/// In Done it needs to be restored as well to prevent any unwanted
/// leftovers which might pose a security issue.
/// </summary>
FAdditionalBufferBackup: Pointer;
/// <summary>
/// Checks whether the state machine is in one of the states specified as
/// parameter. If not a EDECCipherException will be raised.
/// </summary>
/// <param name="States">
/// List of states the state machine should be at currently
/// </param>
/// <exception cref="EDECCipherException">
/// Exception raised if the state machine is not in one of the states
/// specified by the <c>States</c> parameter.
/// </exception>
procedure CheckState(States: TCipherStates);
/// <summary>
/// Initialize the key, based on the key passed in. This is called before
/// OnAfterInitVectorInitialization is called.
/// </summary>
/// <param name="Key">
/// Encryption/Decryption key to be used
/// </param>
/// <param name="Size">
/// Size of the key passed in bytes.
/// </param>
procedure DoInit(const Key; Size: Integer); virtual; abstract;
/// <summary>
/// Allows to run code after the initialization vector has been initialized
/// inside the Init call, which is after DoInit has been called.
/// </summary>
/// <param name="OriginalInitVector">
/// Value of the init vector as originally passed to the Init call without
/// any initialization steps done to/on it
/// </param>
procedure OnAfterInitVectorInitialization(const OriginalInitVector: TBytes); virtual; abstract;
/// <summary>
/// This abstract method needs to be overwritten by each concrete encryption
/// algorithm as this is the routine used internally to encrypt a single
/// block of data.
/// </summary>
/// <param name="Source">
/// Data to be encrypted
/// </param>
/// <param name="Dest">
/// In this memory the encrypted result will be written
/// </param>
/// <param name="Size">
/// Size of source in byte
/// </param>
procedure DoEncode(Source, Dest: Pointer; Size: Integer); virtual; abstract;
/// <summary>
/// This abstract method needs to be overwritten by each concrete encryption
/// algorithm as this is the routine used internally to decrypt a single
/// block of data.
/// </summary>
/// <param name="Source">
/// Data to be decrypted
/// </param>
/// <param name="Dest">
/// In this memory the decrypted result will be written
/// </param>
/// <param name="Size">
/// Size of source in byte
/// </param>
procedure DoDecode(Source, Dest: Pointer; Size: Integer); virtual; abstract;
/// <summary>
/// Securely fills the processing buffer with zeroes to make stealing data
/// from memory harder.
/// </summary>
procedure SecureErase; virtual;
/// <summary>
/// Returns the currently set cipher block mode, means how blocks are
/// linked to each other in order to avoid certain attacks.
/// </summary>
function GetMode: TCipherMode;
/// <summary>
/// Sets the cipher mode, means how each block is being linked with his
/// predecessor to avoid certain attacks
/// </summary>
procedure SetMode(Value: TCipherMode);
/// <summary>
/// When setting a mode it might need to be initialized and that can
/// usually only be done in a child class.
/// </summary>
procedure InitMode; virtual; abstract;
public
/// <summary>
/// List of registered DEC classes. Key is the Identity of the class.
/// </summary>
class var ClassList : TDECClassList;
/// <summary>
/// Tries to find a class type by its name
/// </summary>
/// <param name="Name">
/// Name to look for in the list
/// </param>
/// <returns>
/// Returns the class type if found. if it could not be found a
/// EDECClassNotRegisteredException will be thrown
/// </returns>
/// <exception cref="EDECClassNotRegisteredException">
/// Exception raised if the class specified by <c>Name</c> is not found
/// </exception>
class function ClassByName(const Name: string): TDECCipherClass;
/// <summary>
/// Tries to find a class type by its numeric identity DEC assigned to it.
/// Useful for file headers, so they can easily encode numerically which
/// cipher class was being used.
/// </summary>
/// <param name="Identity">
/// Identity to look for
/// </param>
/// <returns>
/// Returns the class type of the class with the specified identity value
/// or throws an EDECClassNotRegisteredException exception if no class
/// with the given identity has been found
/// </returns>
/// <exception cref="EDECClassNotRegisteredException">
/// Exception raised if the class specified by <c>Identity</c> is not found
/// </exception>
class function ClassByIdentity(Identity: Int64): TDECCipherClass;
/// <summary>
/// Provides meta data about the cipher algorithm used like key size.
/// To be overidden in the concrete cipher classes.
/// </summary>
/// <remarks>
/// C++ does not support virtual static functions thus the base cannot be
/// marked 'abstract'. Calling this version of the method will lead to an
/// EDECAbstractError
/// </remarks>
class function Context: TCipherContext; virtual;
/// <summary>
/// Initializes the instance. Relies in parts on information given by the
/// Context class function.
/// </summary>
constructor Create; override;
/// <summary>
/// Frees internal structures and where necessary does so in a save way so
/// that data in those structures cannot be "stolen". It removes the key
/// from RAM.
/// </summary>
destructor Destroy; override;
/// <summary>
/// Provides information whether the selected block concatenation mode
/// provides authentication functionality or not.
/// </summary>
/// <returns>
/// true if the selected block mode is one providing authentication features
/// as well
/// </returns>
function IsAuthenticated: Boolean;
/// <summary>
/// Initializes the cipher with the necessary encryption/decryption key
/// </summary>
/// <param name="Key">
/// Encryption/decryption key. Recommended/required key length is dependant
/// on the concrete algorithm.
/// </param>
/// <param name="Size">
/// Size of the key in bytes
/// </param>
/// <param name="IVector">
/// Initialization vector. This contains the values the first block of
/// data to be processed is linked with. This is being done the same way
/// as the 2nd block of the data to be processed will be linked with the
/// first block and so on and this is dependant on the cypher mode set via
/// Mode property
/// </param>
/// <param name="IVectorSize">
/// Size of the initialization vector in bytes
/// </param>
/// <param name="IFiller">
/// optional parameter defining the value with which the last block will
/// be filled up if the size of the data to be processed cannot be divided
/// by block size without reminder. Means: if the last block is not
/// completely filled with data.
/// </param>
procedure Init(const Key; Size: Integer; const IVector; IVectorSize: Integer; IFiller: Byte = $FF); overload;
/// <summary>
/// Initializes the cipher with the necessary encryption/decryption key
/// </summary>
/// <param name="Key">
/// Encryption/decryption key. Recommended/required key length is dependant
/// on the concrete algorithm.
/// </param>
/// <param name="IVector">
/// Initialization vector. This contains the values the first block of
/// data to be processed is linked with. This is being done the same way
/// as the 2nd block of the data to be processed will be linked with the
/// first block and so on and this is dependant on the cypher mode set via
/// Mode property
/// </param>
/// <param name="IFiller">
/// optional parameter defining the value with which the last block will
/// be filled up if the size of the data to be processed cannot be divided
/// by block size without reminder. Means: if the last block is not
/// completely filled with data.
/// </param>
procedure Init(const Key: TBytes; const IVector: TBytes; IFiller: Byte = $FF); overload;
/// <summary>
/// Initializes the cipher with the necessary encryption/decryption key
/// </summary>
/// <param name="Key">
/// Encryption/decryption key. Recommended/required key length is dependant
/// on the concrete algorithm.
/// </param>
/// <param name="IVector">
/// Initialization vector. This contains the values the first block of
/// data to be processed is linked with. This is being done the same way
/// as the 2nd block of the data to be processed will be linked with the
/// first block and so on and this is dependant on the cypher mode set via
/// Mode property
/// </param>
/// <param name="IFiller">
/// optional parameter defining the value with which the last block will
/// be filled up if the size of the data to be processed cannot be divided
/// by block size without reminder. Means: if the last block is not
/// completely filled with data.
/// </param>
procedure Init(const Key: RawByteString; const IVector: RawByteString = ''; IFiller: Byte = $FF); overload;
{$IFDEF ANSISTRINGSUPPORTED}
/// <summary>
/// Initializes the cipher with the necessary encryption/decryption key.
/// Only for use with the classic desktop compilers.
/// </summary>
/// <param name="Key">
/// Encryption/decryption key. Recommended/required key length is dependant
/// on the concrete algorithm.
/// </param>
/// <param name="IVector">
/// Initialization vector. This contains the values the first block of
/// data to be processed is linked with. This is being done the same way
/// as the 2nd block of the data to be processed will be linked with the
/// first block and so on and this is dependant on the cypher mode set via
/// Mode property
/// </param>
/// <param name="IFiller">
/// optional parameter defining the value with which the last block will
/// be filled up if the size of the data to be processed cannot be divided
/// by block size without reminder. Means: if the last block is not
/// completely filled with data.
/// </param>
procedure Init(const Key: AnsiString; const IVector: AnsiString = ''; IFiller: Byte = $FF); overload;
{$ENDIF}
{$IFNDEF NEXTGEN}
/// <summary>
/// Initializes the cipher with the necessary encryption/decryption key.
/// Only for use with the classic desktop compilers.
/// </summary>
/// <param name="Key">
/// Encryption/decryption key. Recommended/required key length is dependant
/// on the concrete algorithm.
/// </param>
/// <param name="IVector">
/// Initialization vector. This contains the values the first block of
/// data to be processed is linked with. This is being done the same way
/// as the 2nd block of the data to be processed will be linked with the
/// first block and so on and this is dependant on the cypher mode set via
/// Mode property
/// </param>
/// <param name="IFiller">
/// optional parameter defining the value with which the last block will
/// be filled up if the size of the data to be processed cannot be divided
/// by block size without reminder. Means: if the last block is not
/// completely filled with data.
/// </param>
procedure Init(const Key: WideString; const IVector: WideString = ''; IFiller: Byte = $FF); overload;
{$ENDIF}
/// <summary>
/// Properly finishes the cryptographic operation. It needs to be called
/// at the end of encrypting or decrypting data. It does NOT remove the
/// keys from RAM (this will be done in the destruction only).
/// You can continue encrypting/decrypting without calling Init() again.
/// </summary>
procedure Done; virtual;
// Encoding / Decoding Routines
// Do not add further methods of that kind here! If needed add them to
// TDECFormattedCipher in DECCipherFormats or inherit from that one.
/// <summary>
/// Encrypts the contents of a RawByteString. This method is deprecated
/// and should be replaced by a variant expecting TBytes as source in
/// order to not support mistreating strings as binary buffers.
/// </summary>
/// <remarks>
/// This is the direct successor of the EncodeBinary method from DEC 5.2.
/// When block chaining mode ECBx is used
/// (not recommended!), the size of the data passed via this parameter
/// needs to be a multiple of the block size of the algorithm used,
/// otherwise a EDECCipherException exception will be raised!
/// </remarks>
/// <param name="Source">
/// The data to be encrypted
/// </param>
/// <param name="Format">
/// Optional parameter. Here a formatting method can be passed. The
/// resulting encrypted data will be formatted with this function, if one
/// has been passed. Examples are hex or base 64 formatting.
/// </param>
/// <returns>
/// Encrypted data. Init must have been called previously.
/// </returns>
/// <exception cref="EDECCipherException">
/// Exception raised if the length of the data passed as <c>Source</c>
/// is not a multiple of the algorithm's block size.
/// </exception>
function EncodeRawByteString(const Source: RawByteString;
Format: TDECFormatClass = nil): RawByteString;
deprecated 'please use EncodeBytes functions or TCipherFormats.EncodeStringToString now';
/// <summary>
/// Decrypts the contents of a RawByteString. This method is deprecated
/// and should be replaced by a variant expecting TBytes as source in
/// order to not support mistreating strings as binary buffers.
/// </summary>
/// <remarks>
/// This is the direct successor of the DecodeBinary method from DEC 5.2
/// When block chaining mode ECBx is used
/// (not recommended!), the size of the data passed via this parameter
/// needs to be a multiple of the block size of the algorithm used,
/// otherwise a EDECCipherException exception will be raised!
/// </remarks>
/// <param name="Source">
/// The data to be decrypted
/// </param>
/// <param name="Format">
/// Optional parameter. Here a formatting method can be passed. The
/// data to be decrypted will be formatted with this function, if one
/// has been passed. Examples are hex or base 64 formatting.
/// This is used for removing a formatting applied by the EncodeRawByteString
/// method.
/// </param>
/// <returns>
/// Decrypted data. Init must have been called previously.
/// </returns>
/// <exception cref="EDECCipherException">
/// Exception raised if the length of the data passed as <c>Source</c>
/// is not a multiple of the algorithm's block size.
/// </exception>
function DecodeRawByteString(const Source: RawByteString;
Format: TDECFormatClass = nil): RawByteString; deprecated 'please use DecodeBytes functions now';
/// <summary>
/// Encrypts the contents of a ByteArray.
/// </summary>
/// <param name="Source">
/// The data to be encrypted. When block chaining mode ECBx is used
/// (not recommended!), the size of the data passed via this parameter
/// needs to be a multiple of the block size of the algorithm used,
/// otherwise a EDECCipherException exception will be raised!
/// </param>
/// <param name="Format">
/// Optional parameter. Here a formatting method can be passed. The
/// resulting encrypted data will be formatted with this function, if one
/// has been passed. Examples are hex or base 64 formatting.
/// </param>
/// <returns>
/// Encrypted data. Init must have been called previously.
/// </returns>
/// <exception cref="EDECCipherException">
/// Exception raised if the length of the data passed as <c>Source</c>
/// is not a multiple of the algorithm's block size.
/// </exception>
function EncodeBytes(const Source: TBytes; Format: TDECFormatClass = nil): TBytes;
/// <summary>
/// Decrypts the contents of a ByteArray.
/// </summary>
/// <param name="Source">
/// The data to be decrypted. When block chaining mode ECBx is used
/// (not recommended!), the size of the data passed via this parameter
/// needs to be a multiple of the block size of the algorithm used,
/// otherwise a EDECCipherException exception will be raised!
/// </param>
/// <param name="Format">
/// Optional parameter. Here a formatting method can be passed. The
/// data to be decrypted will be formatted with this function, if one
/// has been passed. Examples are hex or base 64 formatting.
/// This is used for removing a formatting applied by the EncodeRawByteString
/// method.
/// </param>
/// <returns>
/// Decrypted data. Init must have been called previously.
/// </returns>
/// <exception cref="EDECCipherException">
/// Exception raised if the length of the data passed as <c>Source</c>
/// is not a multiple of the algorithm's block size.
/// </exception>
function DecodeBytes(const Source: TBytes; Format: TDECFormatClass = nil): TBytes;
/// <summary>
/// Calculates a Cipher-based message authentication code (CMAC).
/// This is the encryption of the last block concatenation feedback value.
/// In decryption scenarios it can be used to check if the data arrived
/// unaltered if the sender provides the MAC value along with the encrypted
/// text. Both need to match after decrypting. Using this method is less
/// secure than using the HMAC algorithm!
/// This method cannot be used in the ECB cipher mode.
/// Side effect: "Done" will be called if it hasn't been called before.
/// </summary>
/// <param name="Format">
/// Optional parameter. Here a formatting method can be passed. The
/// data to be decrypted will be formatted with this function, if one
/// has been passed. Examples are hex or base 64 formatting.
/// This is used for removing a formatting applied by the EncodeRawByteString
/// method.
/// </param>
/// <returns>
/// Calculates a Cipher-based message authentication code (CMAC).
/// </returns>
/// <exception cref="EDECCipherException">
/// Exception raised the cipher mode is ECB.
/// </exception>
{ TODO: Add unit test }
function CalcMAC(Format: TDECFormatClass = nil): RawByteString;
/// Same as CalcMAC, but return TBytes
function CalcMACBytes(Format: TDECFormatClass = nil): TBytes;
// properties
/// <summary>
/// Provides the size of the initialization vector in bytes.
/// </summary>
property InitVectorSize: Integer
read FBufferSize;
/// <summary>
/// Provides access to the contents of the initialization vector
/// </summary>
property InitVector: PUInt8Array
read FInitializationVector;
/// <summary>
/// Cipher modes are used to derive a stream cipher from block cipher
/// algorithms. For this something from the last entrypted block (or for
/// the first block from the vector) is used in the encryption of the next
/// block. It may be XORed with the next block cipher text for instance.
/// That data "going into the next block encryption" is stored in this
/// feedback array. The size usually depends on the block size of the
/// cipher algorithm.
/// </summary>
property Feedback: PUInt8Array
read FFeedback;
/// <summary>
/// Allows to query the current internal processing state
/// </summary>
property State: TCipherState
read FState;
/// <summary>
/// Mode used for padding data to be encrypted/decrypted. See TCipherMode.
/// </summary>
property Mode: TCipherMode
read GetMode
write SetMode;
/// <summary>
/// Mode used for filling up an incomplete last block in a block cipher
/// </summary>
property FillMode: TBlockFillMode
read FFillMode
write FFillMode;
end;
/// <summary>
/// Returns the passed cipher class type if it is not nil. Otherwise the
/// class type class set per SetDefaultCipherClass is being returned. If using
/// the DECCiphers unit that one registers TCipher_Null in the initialization
/// </summary>
/// <param name="CipherClass">
/// Class type of a cipher class like TCipher_Blowfish or nil, if no
/// encryption/decryption is desired.
/// </param>
/// <returns>
/// Passed class type or defined default cipher class type, depending on
/// CipherClass parameter value.
/// </returns>
function ValidCipher(CipherClass: TDECCipherClass = nil): TDECCipherClass;
/// <summary>
/// Defines which cipher class to return by ValidCipher if passing nil to that
/// </summary>
/// <param name="CipherClass">
/// Class type of a cipher class to return by ValidCipher if passing nil to
/// that one. This parameter should not be nil!
/// </param>
procedure SetDefaultCipherClass(CipherClass: TDECCipherClass);
/// <summary>
/// Provides information whether a certain block concatenation mode
/// provides authentication functionality or not.
/// </summary>
/// <param name="BlockMode">
/// Block mode to check fo authentication features
/// </param>
/// <returns>
/// true if the selected block mode is one providing authentication features
/// as well
/// </returns>
function IsAuthenticatedBlockMode(BlockMode: TCipherMode): Boolean;
implementation
uses
{$IFDEF FPC}
TypInfo,
{$ELSE}
System.TypInfo,
{$ENDIF}
DECUtil;
{$IFOPT Q+}{$DEFINE RESTORE_OVERFLOWCHECKS}{$Q-}{$ENDIF}
{$IFOPT R+}{$DEFINE RESTORE_RANGECHECKS}{$R-}{$ENDIF}
resourcestring
sAlreadyPadded = 'Cipher has already been padded, cannot process message';
sInvalidState = 'Cipher is not in valid state for this action';
sNoKeyMaterialGiven = 'No Keymaterial given (Security Issue)';
sKeyMaterialTooLarge = 'Keymaterial is too large for use (Security Issue)';
sIVMaterialTooLarge = 'Initvector is too large for use (Security Issue)';
sInvalidMACMode = 'Invalid Cipher mode to compute MAC';
sCipherNoDefault = 'No default cipher has been registered';
var
/// <summary>
/// Cipher class returned by ValidCipher if nil is passed as parameter to it
/// </summary>
FDefaultCipherClass: TDECCipherClass = nil;
function ValidCipher(CipherClass: TDECCipherClass): TDECCipherClass;
begin
if CipherClass <> nil then
Result := CipherClass
else
Result := FDefaultCipherClass;
if Result = nil then
raise EDECCipherException.CreateRes(@sCipherNoDefault);
end;
procedure SetDefaultCipherClass(CipherClass: TDECCipherClass);
begin
Assert(Assigned(CipherClass), 'Do not set a nil default cipher class!');
FDefaultCipherClass := CipherClass;
end;
function IsAuthenticatedBlockMode(BlockMode: TCipherMode): Boolean;
begin
Result := BlockMode = cmGCM;
end;
{ TDECCipher }
constructor TDECCipher.Create;
var
MustAdditionalBufferSave: Boolean;
begin
inherited Create;
FBufferSize := Context.BufferSize;
FAdditionalBufferSize := Context.AdditionalBufferSize;
MustAdditionalBufferSave := Context.NeedsAdditionalBufferBackup;
// Initialization vector, feedback, buffer, additional buffer
FDataSize := FBufferSize * 3 + FAdditionalBufferSize;
if MustAdditionalBufferSave then
// if contents of the FAdditionalBuffer needs to be saved increase buffer size
// by FAdditionalBufferSize so FAdditionalBuffer and then FAdditionalBufferBackup
// fit in the buffer
Inc(FDataSize, FAdditionalBufferSize);
// ReallocMemory instead of ReallocMem due to C++ compatibility as per 10.1 help
FData := ReallocMemory(FData, FDataSize);
FInitializationVector := @FData[0];
FInitVectorSize := 0;
FFeedback := @FInitializationVector[FBufferSize];
FBuffer := @FFeedback[FBufferSize];
FAdditionalBuffer := @FBuffer[FBufferSize];
if MustAdditionalBufferSave then
// buffer contents: FData, then FFeedback, then FBuffer then FAdditionalBuffer
FAdditionalBufferBackup := @PUInt8Array(FAdditionalBuffer)[FAdditionalBufferSize]
else
FAdditionalBufferBackup := nil;
FFillMode := fmByte;
FState := csNew;
SecureErase;
end;
destructor TDECCipher.Destroy;
begin
SecureErase;
// FreeMem instead of ReallocMemory which produced a memory leak. ReallocMemory
// was used instead of ReallocMem due to C++ compatibility as per 10.1 help
FreeMem(FData, FDataSize);
FInitializationVector := nil;
FFeedback := nil;
FBuffer := nil;
FAdditionalBuffer := nil;
FAdditionalBufferBackup := nil;
inherited Destroy;
end;
procedure TDECCipher.SetMode(Value: TCipherMode);
begin
if Value <> FMode then
begin
if not (FState in [csNew, csInitialized, csDone]) then
Done;
FMode := Value;
InitMode;
end;
end;
procedure TDECCipher.CheckState(States: TCipherStates);
begin
if not (FState in States) then
begin
if FState = csPadded then
raise EDECCipherException.CreateRes(@sAlreadyPadded)
else
raise EDECCipherException.CreateRes(@sInvalidState);
end;
end;
class function TDECCipher.ClassByIdentity(Identity: Int64): TDECCipherClass;
begin
result := TDECCipherClass(ClassList.ClassByIdentity(Identity));
end;
class function TDECCipher.ClassByName(const Name: string): TDECCipherClass;
begin
result := TDECCipherClass(ClassList.ClassByName(Name));
end;
class function TDECCipher.Context: TCipherContext;
begin
// C++ does not support virtual static functions thus the base cannot be
// marked 'abstract'. This is our workaround:
raise EDECAbstractError.Create(GetShortClassName);
end;
procedure TDECCipher.Init(const Key; Size: Integer; const IVector; IVectorSize: Integer; IFiller: Byte);
var
OriginalInitVector : TBytes;
begin
FState := csNew;
FInitVectorSize := IVectorSize;
SecureErase;
if (Size > Context.KeySize) and (not (ctNull in Context.CipherType)) then
raise EDECCipherException.CreateRes(@sKeyMaterialTooLarge);
if (FInitVectorSize > FBufferSize) and (not (FMode = cmGCM)) then
raise EDECCipherException.CreateRes(@sIVMaterialTooLarge);
DoInit(Key, Size);
if FAdditionalBufferBackup <> nil then
// create backup of FBuffer
Move(FAdditionalBuffer^, FAdditionalBufferBackup^, FAdditionalBufferSize);
FillChar(FInitializationVector^, FBufferSize, IFiller);
SetLength(OriginalInitVector, IVectorSize);
if (IVectorSize > 0) then
Move(IVector, OriginalInitVector[0], IVectorSize);
// GCM needs same treatment as empty IV even if IV specified
if (IVectorSize = 0) or (FMode = cmGCM) then
begin
DoEncode(FInitializationVector, FInitializationVector, FBufferSize);
if FAdditionalBufferBackup <> nil then
// Restore backup fo FBuffer
Move(FAdditionalBufferBackup^, FAdditionalBuffer^, FAdditionalBufferSize);
end
else
Move(IVector, FInitializationVector^, IVectorSize);
OnAfterInitVectorInitialization(OriginalInitVector);
Move(FInitializationVector^, FFeedback^, FBufferSize);
FState := csInitialized;
end;
procedure TDECCipher.Init(const Key: TBytes; const IVector: TBytes; IFiller: Byte = $FF);