-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
CipherBase.pas
1813 lines (1578 loc) · 61.4 KB
/
CipherBase.pas
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
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
CipherBase
Set of base classes for ciphers (encryption/decryption).
At this moment, only base class for symmetric block cipher is implemented
(used for Rijndael/AES), more will probably be implemented later.
Version 1.0.6 (2024-05-02)
Last change 2024-05-02
©2021-2024 František Milt
Contacts:
František Milt: frantisek.milt@gmail.com
Support:
If you find this code useful, please consider supporting its author(s) by
making a small donation using the following link(s):
https://www.paypal.me/FMilt
Changelog:
For detailed changelog and history please refer to this git repository:
github.com/TheLazyTomcat/Lib.CipherBase
Dependencies:
AuxClasses - github.com/TheLazyTomcat/Lib.AuxClasses
* AuxExceptions - github.com/TheLazyTomcat/Lib.AuxExceptions
AuxTypes - github.com/TheLazyTomcat/Lib.AuxTypes
StaticMemoryStream - github.com/TheLazyTomcat/Lib.StaticMemoryStream
StrRect - github.com/TheLazyTomcat/Lib.StrRect
Library AuxExceptions is required only when rebasing local exception classes
(see symbol CipherBase_UseAuxExceptions for details).
Library AuxExceptions might also be required as an indirect dependency.
Indirect dependencies:
SimpleCPUID - github.com/TheLazyTomcat/Lib.SimpleCPUID
UInt64Utils - github.com/TheLazyTomcat/Lib.UInt64Utils
WinFileInfo - github.com/TheLazyTomcat/Lib.WinFileInfo
===============================================================================}
unit CipherBase;
{
CipherBase_UseAuxExceptions
If you want library-specific exceptions to be based on more advanced classes
provided by AuxExceptions library instead of basic Exception class, and don't
want to or cannot change code in this unit, you can define global symbol
CipherBase_UseAuxExceptions to achieve this.
}
{$IF Defined(CipherBase_UseAuxExceptions)}
{$DEFINE UseAuxExceptions}
{$IFEND}
//------------------------------------------------------------------------------
{$IF defined(CPU64) or defined(CPU64BITS)}
{$DEFINE CPU64bit}
{$ELSEIF defined(CPU16)}
{$MESSAGE FATAL '16bit CPU not supported'}
{$ELSE}
{$DEFINE CPU32bit}
{$IFEND}
{$IF Defined(WINDOWS) or Defined(MSWINDOWS)}
{$DEFINE Windows}
{$IFEND}
{$IFDEF FPC}
{$MODE ObjFPC}
{$MODESWITCH ClassicProcVars+}
{$MODESWITCH DuplicateLocals+}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ENDIF}
{$H+}
{$IFOPT Q+}
{$DEFINE OverflowChecks}
{$ENDIF}
interface
uses
SysUtils, Classes,
AuxTypes, AuxClasses{$IFDEF UseAuxExceptions}, AuxExceptions{$ENDIF};
{===============================================================================
Libray-specific exceptions
===============================================================================}
type
ECipherException = class({$IFDEF UseAuxExceptions}EAEGeneralException{$ELSE}Exception{$ENDIF});
ECipherInvalidState = class(ECipherException);
ECipherInvalidValue = class(ECipherException);
ECipherNoStream = class(ECipherException);
{===============================================================================
--------------------------------------------------------------------------------
TCipherBase
--------------------------------------------------------------------------------
===============================================================================}
type
TCipherMode = (cmUndefined,cmEncrypt,cmDecrypt);
TCipherImplementation = (ciPascal,ciAssembly,ciAccelerated);
TCipherImplementations = set of TCipherImplementation;
{===============================================================================
TCipherBase - class declaration
===============================================================================}
type
TCipherBase = class(TCustomObject)
protected
fMode: TCipherMode; // encrypt/decrypt
fStreamBufferSize: TMemSize;
fBufferProgress: Boolean;
fProcessedBytes: TMemSize;
fBreakProcessing: Boolean;
fInitialized: Boolean;
fFinalized: Boolean;
fOnProgressEvent: TFloatEvent;
fOnProgressCallback: TFloatCallback;
// getters, setters
Function GetCipherImplementation: TCipherImplementation; virtual;
procedure SetCipherImplementation(Value: TCipherImplementation); virtual;
Function GetMode: TCipherMode; virtual;
procedure SetMode(Value: TCipherMode); virtual;
procedure SetStreamBufferSize(Value: TMemSize); virtual;
// progress reporting
procedure DoProgress(Progress: Double); virtual;
// main processing
Function UpdateProcessing(const InBuff; InSize: TMemSize; out OutBuff): TMemSize; virtual; abstract;
procedure FinalProcessing(const InBuff; InSize: TMemSize; out OutBuff); virtual; abstract;
// instance initialization/finalization
procedure Initialize; virtual;
procedure Finalize; virtual;
// cipher management methods
{
CiperInit should prepare the cipher for actual processing (eg. construct
the key schedule) based on actual cipher setup.
Called from method Init.
}
procedure CipherInit; virtual; abstract;
{
CipherFinal is there to do a potential cleanup after the processing is
completed.
Called from method Final.
}
procedure CipherFinal; virtual; abstract;
// utility functions
{
IsRunning returns true when initialized and not finalized. It is used to
check whether some fields can be changed, as changing some options during
processing can lead to data corruption.
}
Function IsRunning: Boolean; virtual;
{
RectifyBufferSize normally returns the passed value.
It is here for optimization sake - for example in block ciphers it is better
when the buffer is a multiple of block size.
}
Function RectifyBufferSize(Value: TMemSize): TMemSize; virtual;
public
class Function CipherImplementationsAvailable: TCipherImplementations; virtual;
class Function CipherImplementationsSupported: TCipherImplementations; virtual;
class Function CipherName: String; virtual; abstract;
constructor Create;
destructor Destroy; override;
{
Init must be called before processing using Update and Final methods.
Note that when a cipher is already initialized, calling Init again will
completely re-initialize the cipher.
Sets Initialized to true and Finalized to false.
}
procedure Init; virtual;
{
Update must be able to accept input buffer of any size and produce at most
the same amount of output bytes - meaning OutBuff must be (at least) the
same size as InBuff.
It is allowable to pass the same buffer for input and output - the
implementations must be written to account for this.
Result is the amount of bytes written to OutBuff - can be zero, but cannot
be larger than InSize.
Property Initialized must be set to true and Finalized to false, otherwise
the Update will raise an ECipherInvalidState exception.
}
Function Update(const InBuff; InSize: TMemSize; out OutBuff): TMemSize; virtual;
{
Final accepts buffer of any size, produces final processed data and
finalizes the cipher.
Use function FinalOutputSize just before calling Final to get how many bytes
will be produced by this method (minimal required size of OutBuff).
Sets Finalized to true.
Property Initialized must be true and Finalized false, otherwise final
raises an ECipherInvalidState exception.
}
procedure Final(const InBuff; InSize: TMemSize; out OutBuff); overload; virtual;
{
Following overload of Final only calls the first overload with nil InBuff
and InSize of zero.
}
procedure Final(out OutBuff); overload; virtual;
{
FinalOutputSize calculates the required size of output buffer for a call
to Final.
You must call this method right before a call to Final, otherwise the
returned value might be wrong.
NOTE - default implementation returns InSize, if the result differs from
InSize, do not call inherited code.
}
Function FinalOutputSize(InSize: TMemSize): TMemSize; virtual;
{
OutputSize returns the total size of output after processing all data,
calculated from a given pre-processing size.
WARNING - the output size might depend on current cipher setup, so be sure
to first properly setup the cipher and then obtain this value.
NOTE - default implementation returns InputSize, so if the result differs
from input size, then do not call inherited.
}
Function OutputSize(InputSize: TMemSize): TMemSize; virtual;
// macro methods
{
To get required size for OutBuff, use method OutputSize.
Note that for single-buffer overload, the buffer must be large enough to
fit the output, but the passed size is the size of INPUT data (which might
be smaller).
The same goes for ProcessMemory.
}
procedure ProcessBuffer(const InBuff; InSize: TMemSize; out OutBuff); overload; virtual;
procedure ProcessBuffer(var Buffer; Size: TMemSize); overload; virtual;
procedure ProcessMemory(InMem: Pointer; InSize: TMemSize; OutMem: Pointer); overload; virtual;
procedure ProcessMemory(Memory: Pointer; Size: TMemSize); overload; virtual;
{
WARNING - paramter Count is meant for input, but the cipher can actually
write beyond this limit!
}
procedure ProcessStream(InStream, OutStream: TStream; Count: Int64 = -1); overload; virtual;
procedure ProcessStream(Stream: TStream; Count: Int64 = -1); overload; virtual;
procedure ProcessFile(const InFileName,OutFileName: String); overload; virtual;
procedure ProcessFile(const FileName: String); overload; virtual;
{
ProcessFileMem writes the entire output into a memory stream and then
rewrites the original file with content of this memory stream - note that
it can and will also change the size of the file.
ProcessFileTemp writes output into a temporary file located in the same
directory as input file, then deletes the original file and renames the
temp file to the same name the original had, effectively replacing it.
}
procedure ProcessFileMem(const FileName: String); virtual;
procedure ProcessFileTemp(const FileName: String); virtual;
{
For strings, the output is (re)allocated automatically.
}
procedure ProcessString(const InStr: String; out OutStr: String); overload; virtual;
procedure ProcessString(var Str: String); overload; virtual;
procedure ProcessAnsiString(const InStr: AnsiString; out OutStr: AnsiString); overload; virtual;
procedure ProcessAnsiString(var Str: AnsiString); overload; virtual;
procedure ProcessWideString(const InStr: WideString; out OutStr: WideString); overload; virtual;
procedure ProcessWideString(var Str: WideString); overload; virtual;
// properties
property Mode: TCipherMode read GetMode write SetMode;
{
If cipher is implemented both in assembly and pascal, this property can be
used to discern which implementation is currently used, and also to set
which implementation is to be used next.
Note that when the unit is compiled in PurePascal mode, asm implementation
cannot be used and pascal implementation is always used instead,
irrespective of how you set this property.
}
property CipherImplementation: TCipherImplementation read GetCipherImplementation write SetCipherImplementation;
{
StreamBufferSize is used when allocating read/write buffer for processings
of streams.
}
property StreamBufferSize: TMemSize read fStreamBufferSize write SetStreamBufferSize;
{
When BufferProgress is set to false (default), the progress is reported only
when processing stream or file. When set to true, the progress is reported
from all macro methods.
But note that progress is calculated and reported only on the boundary of
read/write buffer, of which size is set in StreamBufferSize property. This
means that, when processing data smaller than this buffer, no actual
progress is reported, only 0% (0.0) and 100% (1.0).
}
property BufferProgress: Boolean read fBufferProgress write fBufferProgress;
{
ProcessedBytes is number of input bytes processed since a last call to
method Init.
}
property ProcessedBytes: TMemSize read fProcessedBytes write fProcessedBytes;
{
BreakProcessing, when set to true inside of progress event or callback,
will cause premature termination of processing right after return from the
call.
}
property BreakProcessing: Boolean read fBreakProcessing write fBreakProcessing;
property Initialized: Boolean read fInitialized;
property Finalized: Boolean read fFinalized;
{
Progress is reported only from macro methods (ProcessStream, ProcessFile,
...).
Progress value is normalized, meaning it is reported in the range <0,1>.
If both event and callback are assigned, then only the event is called.
}
property OnProgress: TFloatEvent read fOnProgressEvent write fOnProgressEvent;
property OnProgressEvent: TFloatEvent read fOnProgressEvent write fOnProgressEvent;
property OnProgressCallback: TFloatCallback read fOnProgressCallback write fOnProgressCallback;
end;
{===============================================================================
--------------------------------------------------------------------------------
TBlockCipher
--------------------------------------------------------------------------------
===============================================================================}
type
TBlockCipherModeOfOperation = (moECB,moCBC,moPCBC,moCFB,moOFB,moCTR);
TBlockCipherPadding = (padZeroes,padPKCS7,padANSIX923,padISO10126,padISOIEC7816_4);
TBlockCipherUpdateProc = procedure(const Input; out Output) of object;
{===============================================================================
TBlockCipher - class declaration
===============================================================================}
type
TBlockCipher = class(TCipherBase)
protected
fModeOfOperation: TBlockCipherModeOfOperation;
fPadding: TBlockCipherPadding;
fBlockBytes: TMemSize;
fInitVector: Pointer;
fKey: Pointer;
fKeyBytes: TMemSize;
// internals...
fInTransferData: Pointer; // input data not consumed in previous processing
fInTransferSize: TMemSize; // allocated size input transfer buffer
fInTransferCount: TMemSize; // number of input bytes not consumed in previous processing
fOutTransferData: Pointer; // output data not consumed in previous processing
fOutTransferSize: TMemSize; // allocated size output transfer buffer
fOutTransferCount: TMemSize; // number of output bytes not consumed in previous processing
fTempBlock: Pointer; // used only in BlockUpdate_* methods, do not use anywhere else!
fOutBuffer: Pointer;
fOutBufferSize: TMemSize;
fBlockUpdateProc: TBlockCipherUpdateProc;
// getters, setters
procedure SetModeOfOperation(Value: TBlockCipherModeOfOperation); virtual;
procedure SetBlockBytes(Value: TMemSize); virtual;
Function GetBlockBits: Integer; virtual;
procedure SetBlockBits(Value: Integer); virtual;
procedure SetInitVector(Value: Pointer); virtual;
procedure SetKey(Value: Pointer); virtual;
procedure SetKeyBytes(Value: TMemSize); virtual;
Function GetKeyBits: Integer; virtual;
procedure SetKeyBits(Value: Integer); virtual;
// block utility functions
procedure BlockXOR(const Src1,Src2; out Dest); virtual;
procedure BlockCopy(const Src; out Dest); virtual;
procedure BlockPad(var Block; UsedBytes: TMemSize); virtual;
// block update methods for different modes of operation
procedure BlockUpdate_ECB(const Input; out Output); virtual;
procedure BlockUpdate_CBC(const Input; out Output); virtual;
procedure BlockUpdate_PCBC(const Input; out Output); virtual;
procedure BlockUpdate_CFB(const Input; out Output); virtual;
procedure BlockUpdate_OFB(const Input; out Output); virtual;
procedure BlockUpdate_CTR(const Input; out Output); virtual;
// processing of individual blocks
procedure BlockEncrypt(const Input; out Output); virtual; abstract;
procedure BlockDecrypt(const Input; out Output); virtual; abstract;
// processing helpers
Function PutToInTransfer(Buff: Pointer; Size: TMemSize): TMemSize; virtual;
Function TakeFromOutTransfer(Buff: Pointer; Size: TMemSize; ShiftDown: Boolean = True): TMemSize; virtual;
// main processing
Function UpdateProcessingFast(const InBuff; InSize: TMemSize; out OutBuff): TMemSize; virtual;
Function UpdateProcessingSlow(const InBuff; InSize: TMemSize; out OutBuff): TMemSize; virtual;
Function UpdateProcessing(const InBuff; InSize: TMemSize; out OutBuff): TMemSize; override;
procedure FinalProcessing(const InBuff; InSize: TMemSize; out OutBuff); override;
// internal cipher setup
procedure CipherSetup(Mode: TCipherMode; ModeOfOperation: TBlockCipherModeOfOperation; Key, InitVector: Pointer; KeyBytes, BlockBytes: TMemSize); virtual;
// initialization/finalization
procedure Initialize; override;
procedure Finalize; override;
// utility functions
Function RectifyBufferSize(Value: TMemSize): TMemSize; override;
public
constructor CreateForEncryption(ModeOfOperation: TBlockCipherModeOfOperation; const Key; const InitVector; KeyBytes, BlockBytes: TMemSize); overload; virtual;
constructor CreateForEncryption(ModeOfOperation: TBlockCipherModeOfOperation; const Key; KeyBytes, BlockBytes: TMemSize); overload; virtual;
constructor CreateForEncryption(const Key; KeyBytes, BlockBytes: TMemSize); overload; virtual;
constructor CreateForDecryption(ModeOfOperation: TBlockCipherModeOfOperation; const Key; const InitVector; KeyBytes, BlockBytes: TMemSize{$IFNDEF FPC}; Dummy: Integer = 0{$ENDIF}); overload; virtual;
constructor CreateForDecryption(ModeOfOperation: TBlockCipherModeOfOperation; const Key; KeyBytes, BlockBytes: TMemSize{$IFNDEF FPC}; Dummy: Integer = 0{$ENDIF}); overload; virtual;
constructor CreateForDecryption(const Key; KeyBytes, BlockBytes: TMemSize{$IFNDEF FPC}; Dummy: Integer = 0{$ENDIF}); overload; virtual;
procedure SetupEncryption(ModeOfOperation: TBlockCipherModeOfOperation; const Key; const InitVector; KeyBytes, BlockBytes: TMemSize); overload; virtual;
procedure SetupEncryption(ModeOfOperation: TBlockCipherModeOfOperation; const Key; KeyBytes, BlockBytes: TMemSize); overload; virtual;
procedure SetupEncryption(const Key; KeyBytes, BlockBytes: TMemSize); overload; virtual;
procedure SetupDecryption(ModeOfOperation: TBlockCipherModeOfOperation; const Key; const InitVector; KeyBytes, BlockBytes: TMemSize); overload; virtual;
procedure SetupDecryption(ModeOfOperation: TBlockCipherModeOfOperation; const Key; KeyBytes, BlockBytes: TMemSize); overload; virtual;
procedure SetupDecryption(const Key; KeyBytes, BlockBytes: TMemSize); overload; virtual;
procedure Init; override;
Function FinalOutputSize(InSize: TMemSize): TMemSize; override;
Function OutputSize(InputSize: TMemSize): TMemSize; override;
property ModeOfOperation: TBlockCipherModeOfOperation read fModeOfOperation write SetModeOfOperation;
property Padding: TBlockCipherPadding read fPadding write fPadding;
property BlockBytes: TMemSize read fBlockBytes write SetBlockBytes;
property BlockBits: Integer read GetBlockBits write SetBlockBits;
property InitVector: Pointer read fInitVector write SetInitVector;
property InitVectorBytes: TMemSize read fBlockBytes;
property InitVectorBits: Integer read GetBlockBits;
property Key: Pointer read fKey write SetKey;
property KeyBytes: TMemSize read fKeyBytes write SetKeyBytes;
property KeyBits: Integer read GetKeyBits write SetKeyBits;
end;
implementation
uses
{$IF not Defined(FPC) and Defined(Windows)}Windows,{$IFEND}
StrRect, StaticMemoryStream;
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W4055:={$WARN 4055 OFF}} // Conversion between ordinals and pointers is not portable
{$DEFINE W5024:={$WARN 5024 OFF}} // Parameter "$1" not used
{$ENDIF}
{===============================================================================
--------------------------------------------------------------------------------
TCipherBase
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TCipherBase - utility functions
===============================================================================}
// so there is no need to link Math unit
Function Min(A,B: Int64): Int64;
begin
If A < B then
Result := A
else
Result := B;
end;
//------------------------------------------------------------------------------
{$IFDEF OverflowChecks}{$Q-}{$ENDIF}
Function OffsetPtr(Ptr: Pointer; Offset: PtrInt): Pointer;
begin
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
Result := Pointer(PtrUInt(Ptr) + PtrUInt(Offset));
{$IFDEF FPCDWM}{$POP}{$ENDIF}
end;
{$IFDEF OverflowChecks}{$Q+}{$ENDIF}
//------------------------------------------------------------------------------
procedure ShiftBufferDown(Ptr: Pointer; Offset,BufferSize: TMemSize);
begin
If (Offset <> 0) and (Offset < BufferSize) then
Move(OffsetPtr(Ptr,Offset)^,Ptr^,BufferSize - Offset);
end;
//------------------------------------------------------------------------------
Function CntrCorrectEndian(Value: UInt16): UInt16; overload;
begin
{$IFDEF ENDIAN_BIG}
Result := Value;
{$ELSE}
Result := ((Value and $FF00) shr 8) or ((Value and $00FF) shl 8);
{$ENDIF}
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function CntrCorrectEndian(Value: UInt32): UInt32; overload;
begin
{$IFDEF ENDIAN_BIG}
Result := Value;
{$ELSE}
Result := ((Value and $FF000000) shr 24) or ((Value and $00FF0000) shr 8) or
((Value and $0000FF00) shl 8) or ((Value and $000000FF) shl 24);
{$ENDIF}
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function CntrCorrectEndian(Value: UInt64): UInt64; overload;
begin
{$IFDEF ENDIAN_BIG}
Result := Value;
{$ELSE}
Int64Rec(Result).Lo := CntrCorrectEndian(Int64Rec(Value).Hi);
Int64Rec(Result).Hi := CntrCorrectEndian(Int64Rec(Value).Lo);
{$ENDIF}
end;
{===============================================================================
TCipherBase - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TCipherBase - protected methods
-------------------------------------------------------------------------------}
Function TCipherBase.GetCipherImplementation: TCipherImplementation;
begin
Result := ciPascal;
end;
//------------------------------------------------------------------------------
{$IFDEF FPCDWM}{$PUSH}W5024{$ENDIF}
procedure TCipherBase.SetCipherImplementation(Value: TCipherImplementation);
begin
// do nothing;
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
//------------------------------------------------------------------------------
Function TCipherBase.GetMode: TCipherMode;
begin
Result := fMode;
end;
//------------------------------------------------------------------------------
procedure TCipherBase.SetMode(Value: TCipherMode);
begin
If not IsRunning then
begin
If Value in [cmEncrypt,cmDecrypt] then
fMode := Value
else
raise ECipherInvalidValue.CreateFmt('TCipherBase.SetMode: Invalid mode (%d).',[Ord(Value)]);
end
else raise ECipherInvalidState.Create('TCipherBase.SetMode: Cannot change mode on running cipher.');
end;
//------------------------------------------------------------------------------
procedure TCipherBase.SetStreamBufferSize(Value: TMemSize);
begin
If Value > 0 then
fStreamBufferSize := Value
else
raise ECipherInvalidValue.CreateFmt('TCipherBase.SetStreamBufferSize: Invalid size (%d).',[Ord(Value)]);
end;
//------------------------------------------------------------------------------
procedure TCipherBase.DoProgress(Progress: Double);
begin
If Assigned(fOnProgressEvent) then
fOnProgressEvent(Self,Progress)
else If Assigned(fOnProgressCallback) then
fOnProgressCallback(Self,Progress);
end;
//------------------------------------------------------------------------------
procedure TCipherBase.Initialize;
begin
fMode := cmUndefined;
fStreamBufferSize := 1024 * 1024; // 1MiB
fBufferProgress := False;
fProcessedBytes := 0;
fBreakProcessing := False;
fInitialized := False;
fFinalized := False;
fOnProgressEvent := nil;
fOnProgressCallback := nil;
end;
//------------------------------------------------------------------------------
procedure TCipherBase.Finalize;
begin
// nothing to do
end;
//------------------------------------------------------------------------------
Function TCipherBase.IsRunning: Boolean;
begin
Result := fInitialized and not fFinalized;
end;
//------------------------------------------------------------------------------
Function TCipherBase.RectifyBufferSize(Value: TMemSize): TMemSize;
begin
Result := Value;
end;
{-------------------------------------------------------------------------------
TCipherBase - public methods
-------------------------------------------------------------------------------}
class Function TCipherBase.CipherImplementationsAvailable: TCipherImplementations;
begin
Result := [ciPascal];
end;
//------------------------------------------------------------------------------
class Function TCipherBase.CipherImplementationsSupported: TCipherImplementations;
begin
Result := [ciPascal];
end;
//------------------------------------------------------------------------------
constructor TCipherBase.Create;
begin
inherited Create;
Initialize;
end;
//------------------------------------------------------------------------------
destructor TCipherBase.Destroy;
begin
Finalize;
inherited;
end;
//------------------------------------------------------------------------------
procedure TCipherBase.Init;
begin
If fMode in [cmEncrypt,cmDecrypt] then
begin
fProcessedBytes := 0;
fInitialized := True;
fFinalized := False;
CipherInit;
end
else raise ECipherInvalidState.CreateFmt('TCipherBase.Init: Invalid cipher mode (%d).',[Ord(fMode)]);
end;
//------------------------------------------------------------------------------
Function TCipherBase.Update(const InBuff; InSize: TMemSize; out OutBuff): TMemSize;
begin
If fInitialized then
begin
If not fFinalized then
begin
Result := UpdateProcessing(InBuff,InSize,OutBuff);
Inc(fProcessedBytes,InSize);
end
else raise ECipherInvalidState.Create('TCipherBase.Update: Cipher already finalized.');
end
else raise ECipherInvalidState.Create('TCipherBase.Update: Cipher not initialized.');
end;
//------------------------------------------------------------------------------
procedure TCipherBase.Final(const InBuff; InSize: TMemSize; out OutBuff);
begin
If fInitialized then
begin
If not fFinalized then
begin
FinalProcessing(InBuff,InSize,OutBuff);
Inc(fProcessedBytes,InSize);
fFinalized := True;
CipherFinal;
end
else raise ECipherInvalidState.Create('TCipherBase.Final: Cipher already finalized.');
end
else raise ECipherInvalidState.Create('TCipherBase.Final: Cipher not initialized.');
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure TCipherBase.Final(out OutBuff);
begin
Final(nil^,0,OutBuff);
end;
//------------------------------------------------------------------------------
Function TCipherBase.FinalOutputSize(InSize: TMemSize): TMemSize;
begin
Result := InSize;
end;
//------------------------------------------------------------------------------
Function TCipherBase.OutputSize(InputSize: TMemSize): TMemSize;
begin
Result := InputSize;
end;
//------------------------------------------------------------------------------
procedure TCipherBase.ProcessBuffer(const InBuff; InSize: TMemSize; out OutBuff);
var
InStream: TStaticMemoryStream;
OutStream: TWritableStaticMemoryStream;
begin
If fBufferProgress then
begin
InStream := TStaticMemoryStream.Create(@InBuff,InSize);
try
OutStream := TWritableStaticMemoryStream.Create(@OutBuff,OutputSize(InSize));
try
ProcessStream(InStream,OutStream);
finally
OutStream.Free;
end;
finally
InStream.Free;
end;
end
else
begin
Init;
Final(InBuff,InSize,OutBuff);
end;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure TCipherBase.ProcessBuffer(var Buffer; Size: TMemSize);
var
Stream: TWritableStaticMemoryStream;
begin
If fBufferProgress then
begin
Stream := TWritableStaticMemoryStream.Create(@Buffer,OutputSize(Size));
try
Stream.Seek(0,soBeginning);
ProcessStream(Stream,Size);
finally
Stream.Free;
end;
end
else
begin
Init;
Final(Buffer,Size,Buffer);
end;
end;
//------------------------------------------------------------------------------
procedure TCipherBase.ProcessMemory(InMem: Pointer; InSize: TMemSize; OutMem: Pointer);
begin
ProcessBuffer(InMem^,InSize,OutMem^);
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure TCipherBase.ProcessMemory(Memory: Pointer; Size: TMemSize);
begin
ProcessBuffer(Memory^,Size);
end;
//------------------------------------------------------------------------------
procedure TCipherBase.ProcessStream(InStream, OutStream: TStream; Count: Int64 = -1);
var
Buffer: Pointer;
BuffSize: TMemSize;
BytesRead: LongInt;
BytesOutput: TMemSize;
InitCount: Int64;
begin
If InStream = OutStream then
ProcessStream(InStream)
else
begin
If not Assigned(InStream) then
raise ECipherNoStream.Create('TCipherBase.ProcessStream: Input stream not assigned.');
If not Assigned(OutStream) then
raise ECipherNoStream.Create('TCipherBase.ProcessStream: Output stream not assigned.');
If Count = 0 then
Count := InStream.Size - InStream.Position;
If Count < 0 then
begin
InStream.Seek(0,soBeginning);
Count := InStream.Size;
end;
InitCount := Count;
BuffSize := RectifyBufferSize(fStreamBufferSize);
fBreakProcessing := False;
DoProgress(0.0);
If not fBreakProcessing then
begin
GetMem(Buffer,BuffSize);
try
Init;
BytesRead := 0;
If InitCount > 0 then
repeat
BytesRead := InStream.Read(Buffer^,Min(BuffSize,Count));
// process only whole buffers
If TMemSize(BytesRead) >= BuffSize then
begin
BytesOutput := Update(Buffer^,BytesRead,Buffer^);
{
Note that WriteBuffer can fail on static streams, but that is
a desired behaviour, as static stream are not supposed to be
used as output.
}
OutStream.WriteBuffer(Buffer^,BytesOutput);
Dec(Count,BytesRead);
DoProgress((InitCount - Count) / InitCount);
end;
until (TMemSize(BytesRead) < BuffSize) or fBreakProcessing;
{
By now, the buffer is either empty, or contains less data than
BuffSize. Realloc the memory so it can fit data from Final (original
data are preserved).
}
If not fBreakProcessing then
begin
BuffSize := FinalOutputSize(BytesRead);
ReallocMem(Buffer,BuffSize);
// do final processing
Final(Buffer^,BytesRead,Buffer^);
OutStream.WriteBuffer(Buffer^,BuffSize);
DoProgress(1.0);
end;
finally
FreeMem(Buffer,BuffSize);
end;
end;
end;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure TCipherBase.ProcessStream(Stream: TStream; Count: Int64 = -1);
var
Buffer: Pointer;
BuffSize: TMemSize;
BytesRead: LongInt;
BytesOutput: TMemSize;
InitCount: Int64;
WritePos: Int64;
ReadPos: Int64;
begin
If Assigned(Stream) then
begin
If Count = 0 then
Count := Stream.Size - Stream.Position;
If Count < 0 then
begin
Stream.Seek(0,soBeginning);
Count := Stream.Size;
end;
InitCount := Count;
BuffSize := RectifyBufferSize(fStreamBufferSize);
fBreakProcessing := False;
DoProgress(0.0);
If not fBreakProcessing then
begin
GetMem(Buffer,BuffSize);
try
Init;
WritePos := Stream.Position;
ReadPos := Stream.Position;
BytesRead := 0;
If InitCount > 0 then
repeat
Stream.Seek(ReadPos,soBeginning);
BytesRead := Stream.Read(Buffer^,Min(BuffSize,Count));
ReadPos := ReadPos + Int64(BytesRead);
If TMemSize(BytesRead) >= BuffSize then
begin
BytesOutput := Update(Buffer^,BytesRead,Buffer^);
If BytesOutput > 0 then
begin
Stream.Seek(WritePos,soBeginning);
Stream.WriteBuffer(Buffer^,BytesOutput);
WritePos := WritePos + Int64(BytesOutput);
end;
Dec(Count,BytesRead);
DoProgress((InitCount - Count) / InitCount);
end;
until (TMemSize(BytesRead) < BuffSize) or fBreakProcessing;
If not fBreakProcessing then
begin
BuffSize := FinalOutputSize(BytesRead);
ReallocMem(Buffer,BuffSize);
Final(Buffer^,BytesRead,Buffer^);
Stream.Seek(WritePos,soBeginning);
Stream.WriteBuffer(Buffer^,BuffSize);
DoProgress(1.0);
end;
finally
FreeMem(Buffer,BuffSize);
end;
end;
end
else raise ECipherNoStream.Create('TCipherBase.ProcessStream: Stream not assigned.');
end;
//------------------------------------------------------------------------------
procedure TCipherBase.ProcessFile(const InFileName,OutFileName: String);
var
InFileStream: TFileStream;
OutFileStream: TFileStream;
begin
InFileStream := TFileStream.Create(StrToRTL(InFileName),fmOpenRead or fmShareDenyWrite);
try
OutFileStream := TFileStream.Create(StrToRTL(OutFileName),fmCreate or fmShareDenyWrite);
try
ProcessStream(InFileStream,OutFileStream);
finally
OutFileStream.Free;
end;
finally
InFileStream.Free;
end;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure TCipherBase.ProcessFile(const FileName: String);
var
FileStream: TFileStream;
begin
FileStream := TFileStream.Create(StrToRTL(FileName),fmOpenReadWrite or fmShareDenyWrite);
try
ProcessStream(FileStream);
finally
FileStream.Free;
end;
end;
//------------------------------------------------------------------------------
procedure TCipherBase.ProcessFileMem(const FileName: String);
var
InFileStream: TFileStream;
OutputStream: TMemoryStream;
begin
InFileStream := TFileStream.Create(StrToRTL(FileName),fmOpenReadWrite or fmShareDenyWrite);
try
OutputStream := TMemoryStream.Create;
try
// preallocate the memory
OutputStream.Size := Int64(OutputSize(InFileStream.Size));
OutputStream.Seek(0,soBeginning);
// processing...
ProcessStream(InFileStream,OutputStream);
// save result
InFileStream.Seek(0,soBeginning);
InFileStream.CopyFrom(OutputStream,0);
If InFileStream.Size <> OutputStream.Size then
InFileStream.Size := OutputStream.Size;
finally
OutputStream.Free;
end;
finally
InFileStream.Free;
end;
end;
//------------------------------------------------------------------------------
procedure TCipherBase.ProcessFileTemp(const FileName: String);
var