-
-
Notifications
You must be signed in to change notification settings - Fork 324
/
SynCrypto.pas
15571 lines (14688 loc) · 547 KB
/
SynCrypto.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
/// fast cryptographic routines (hashing and cypher)
// - implements AES,XOR,ADLER32,MD5,RC4,SHA1,SHA256,SHA384,SHA512,SHA3 and JWT
// - optimized for speed (tuned assembler and SSE3/SSE4/AES-NI/PADLOCK support)
// - this unit is a part of the freeware Synopse mORMot framework,
// licensed under a MPL/GPL/LGPL tri-license; version 1.18
unit SynCrypto;
(*
This file is part of Synopse framework.
Synopse framework. Copyright (c) Arnaud Bouchez
Synopse Informatique - https://synopse.info
*** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
The Original Code is Synopse mORMot framework.
The Initial Developer of the Original Code is Arnaud Bouchez.
Portions created by the Initial Developer are Copyright (c)
the Initial Developer. All Rights Reserved.
Contributor(s):
- Alfred Glaenzer (alf)
- Eric Grange for SHA-3 MMX asm optimization
- EvaF
- Intel's sha256_sse4.asm under under a three-clause Open Software license
- Johan Bontes
- souchaud
- Project Nayuki (MIT License) for SHA-512 optimized x86 asm
- Wolfgang Ehrhardt under zlib license for SHA-3 and AES "pure pascal" code
- Maxim Masiutin for the MD5 asm
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****
Synopse Cryptographic routines
==============================
- fastest ever 100% Delphi (and asm ;) code
- AES Crypto(128,192,256 bits key) with optimized asm version
and multi-threaded code for multi-core CPU for blocks > 512 KB
- XOR Crypto (32 bits key) - very fast with variable or fixed key
- RC4 Crypto - weak, but simple and standard (used e.g. by SynPdf)
- ADLER32 - 32 bits fast Hash with optimized asm version
- MD5 - standard fast 128 bits Hash
- SHA-1 - 160 bits Secure Hash
- SHA-256 - 256 bits Secure Hash with optimized asm version
- SHA-512 - 512 bits Secure Hash with optimized asm version (with SHA-384)
- SHA-3 - 224/256/384/512/Shake algorithms based on Keccak permutation
- hardware AES-NI and SHA-SSE4 support for latest CPU
- VIA PADLOCK optional support - native .o code on linux or .dll (Win32)
(tested on a Dedibox C7 (rev1) linux server - need validation for Win32)
- Microsoft AES Cryptographic Provider optional support via CryptoAPI
*)
interface
{$I Synopse.inc} // define HASINLINE CPU32 CPU64 OWNNORMTOUPPER
{.$define USEPADLOCK}
{.$define AESPASCAL} // for debug
{$ifdef Linux}
{$undef USETHREADSFORBIGAESBLOCKS} // uses low-level WinAPI threading
{$ifdef KYLIX3}
{.$define USEPADLOCK} // dedibox Linux tested only
{$endif}
{$else}
{$ifndef DELPHI5OROLDER}
// on Windows: enable Microsoft AES Cryptographic Provider (XP SP3 and up)
{$define USE_PROV_RSA_AES}
{$endif}
// on Windows: will use Threads for very big blocks (>512KB) if multi-CPU
{$define USETHREADSFORBIGAESBLOCKS}
{$endif}
{$ifdef USEPADLOCK}
{$ifdef MSWINDOWS}
{$define USEPADLOCKDLL} // Win32: we can use LibPadlock.dll
{$else}
{.$define PADLOCKDEBUG} // display message before using padlock
{.$define USEPADLOCKDLL} // Linux: use fast .o linked code
{$endif}
{$endif}
uses
{$ifdef MSWINDOWS}
Windows,
{$else}
{$ifdef KYLIX3}
LibC,
SynKylix,
{$endif}
{$ifdef FPC}
BaseUnix,
SynFPCLinux,
{$endif FPC}
{$endif MSWINDOWS}
SysUtils,
{$ifndef LVCL}
{$ifndef DELPHI5OROLDER}
RTLConsts,
{$endif}
{$endif LVCL}
Classes,
SynLZ, // already included in SynCommons, and used by CompressShaAes()
SynCommons,
SynTable; // for TSynUniqueIdentifierGenerator
{$ifdef ABSOLUTEPASCAL}
{$define AES_PASCAL}
{$define SHA3_PASCAL}
{$else}
{$ifdef DELPHI5OROLDER}
{$define AES_PASCAL} // Delphi 5 internal asm is buggy :(
{$define SHA3_PASCAL}
{$define SHA512_X86} // external sha512-x86.obj
{$else}
{$ifdef CPUINTEL} // AES-NI supported for x86 and x64 under Windows
{$ifdef CPU64}
{$ifdef HASAESNI}
{$define USEAESNI}
{$define USEAESNI64}
{$else}
{$define AES_PASCAL} // Delphi XE2/XE3 do not have the AES-NI opcodes :(
{$endif}
{$define AESPASCAL_OR_CPU64}
{$ifndef BSD}
{$define CRC32C_X64} // external crc32_iscsi_01 for win64/lin64
{$define SHA512_X64} // external sha512_sse4 for win64/lin64
{$endif}
{$else}
{$ifdef MSWINDOWS}
{$define SHA512_X86} // external sha512-x86.obj/.o
{$endif}
{$ifdef ABSOLUTEPASCAL}
{$define AES_PASCAL} // x86 AES asm below is not PIC-safe
{$else}
{$define CPUX86_NOTPIC}
{$endif ABSOLUTEPASCAL}
{$ifdef FPC}
{$ifdef DARWIN}
{$define AES_PASCAL} // as reported by alf
{$endif DARWIN}
{$ifdef LINUX}
{$ifndef AES_PASCAL}
{$define SHA512_X86} // external linux32/sha512-x86.o
{$endif AES_PASCAL}
{$endif}
{$endif FPC}
{$ifndef AES_PASCAL}
{$define USEAESNI} // some functions are not PIC-safe
{$define USEAESNI32}
{$endif AES_PASCAL}
{$endif}
{$else}
{$define AES_PASCAL}
{$define SHA3_PASCAL}
{$endif CPUINTEL}
{$endif}
{$endif}
{$ifdef AES_PASCAL}
{$define AESPASCAL_OR_CPU64}
{$endif}
{.$define AES_ROLLED}
// if defined, use rolled version, which is slightly slower (at least on my CPU)
{$ifndef AESPASCAL_OR_CPU64}
{$define AES_ROLLED} // asm requires rolled decryption keys
{$endif}
{$ifdef CPUX64}
{$define AES_ROLLED} // asm requires rolled decryption keys
{$endif}
{$ifdef USEPADLOCK}
var
/// if dll/so and VIA padlock compatible CPU are present
padlock_available: boolean = false;
{$endif}
const
/// hide all AES Context complex code
AESContextSize = 276+sizeof(pointer){$ifdef USEPADLOCK}*2{$endif}
{$ifdef USEAESNI32}+sizeof(pointer){$endif};
/// hide all SHA-1/SHA-2 complex code by storing the context as buffer
SHAContextSize = 108;
/// hide all SHA-3 complex code by storing the Keccak Sponge as buffer
SHA3ContextSize = 412;
/// power of two for a standard AES block size during cypher/uncypher
// - to be used as 1 shl AESBlockShift or 1 shr AESBlockShift for fast div/mod
AESBlockShift = 4;
/// bit mask for fast modulo of AES block size
AESBlockMod = 15;
/// maximum AES key size (in bytes)
AESKeySize = 256 div 8;
type
/// class of Exceptions raised by this unit
ESynCrypto = class(ESynException);
/// 128 bits memory block for AES data cypher/uncypher
TAESBlock = THash128;
/// points to a 128 bits memory block, as used for AES data cypher/uncypher
PAESBlock = ^TAESBlock;
/// 256 bits memory block for maximum AES key storage
TAESKey = THash256;
/// stores an array of THash128 to check for their unicity
// - used e.g. to implement TAESAbstract.IVHistoryDepth property, but may be
// also used to efficiently store a list of 128-bit IPv6 addresses
{$ifdef USERECORDWITHMETHODS}THash128History = record
{$else}THash128History = object{$endif}
private
Previous: array of THash128Rec;
Index: integer;
public
/// how many THash128 values can be stored
Depth: integer;
/// how many THash128 values are currently stored
Count: integer;
/// initialize the storage for a given history depth
// - if Count reaches Depth, then older items will be removed
procedure Init(size, maxsize: integer);
/// O(n) fast search of a hash value in the stored entries
// - returns true if the hash was found, or false if it did not appear
function Exists(const hash: THash128): boolean;
{$ifdef HASINLINE}inline;{$endif}
/// add a hash value to the stored entries, checking for duplicates
// - returns true if the hash was added, or false if it did already appear
function Add(const hash: THash128): boolean;
end;
PAES = ^TAES;
/// handle AES cypher/uncypher
// - this is the default Electronic codebook (ECB) mode
// - this class will use AES-NI hardware instructions, if available
{$ifdef USEPADLOCK}
// - this class will use VIA PadLock instructions, if available
{$endif}
// - we defined a record instead of a class, to allow stack allocation and
// thread-safe reuse of one initialized instance (warning: not for Padlock)
{$ifdef USERECORDWITHMETHODS}TAES = record
{$else}TAES = object{$endif}
private
Context: packed array[1..AESContextSize] of byte;
{$ifdef USEPADLOCK}
function DoPadlockInit(const Key; KeySize: cardinal): boolean;
{$endif}
public
/// Initialize AES contexts for cypher
// - first method to call before using this object for encryption
// - KeySize is in bits, i.e. 128,192,256
function EncryptInit(const Key; KeySize: cardinal): boolean;
/// encrypt an AES data block into another data block
procedure Encrypt(const BI: TAESBlock; var BO: TAESBlock); overload;
/// encrypt an AES data block
procedure Encrypt(var B: TAESBlock); overload;
/// Initialize AES contexts for uncypher
// - first method to call before using this object for decryption
// - KeySize is in bits, i.e. 128,192,256
function DecryptInit(const Key; KeySize: cardinal): boolean;
/// Initialize AES contexts for uncypher, from another TAES.EncryptInit
function DecryptInitFrom(const Encryption{$ifndef DELPHI5OROLDER}: TAES{$endif};
const Key; KeySize: cardinal): boolean;
/// decrypt an AES data block
procedure Decrypt(var B: TAESBlock); overload;
/// decrypt an AES data block into another data block
procedure Decrypt(const BI: TAESBlock; var BO: TAESBlock); overload;
/// Finalize AES contexts for both cypher and uncypher
// - would fill the TAES instance with zeros, for safety
// - is only mandatoy when padlock is used
procedure Done;
/// generic initialization method for AES contexts
// - call either EncryptInit() either DecryptInit() method
function DoInit(const Key; KeySize: cardinal; doEncrypt: boolean): boolean;
/// perform the AES cypher or uncypher to continuous memory blocks
// - call either Encrypt() either Decrypt() method
procedure DoBlocks(pIn, pOut: PAESBlock; out oIn, oOut: PAESBLock; Count: integer; doEncrypt: boolean); overload;
/// perform the AES cypher or uncypher to continuous memory blocks
// - call either Encrypt() either Decrypt() method
procedure DoBlocks(pIn, pOut: PAESBlock; Count: integer; doEncrypt: boolean); overload;
{$ifdef USETHREADSFORBIGAESBLOCKS}
/// perform the AES cypher or uncypher to continuous memory blocks
// - this special method will use Threads for bigs blocks (>512KB) if multi-CPU
// - call either Encrypt() either Decrypt() method
procedure DoBlocksThread(var bIn, bOut: PAESBlock; Count: integer; doEncrypt: boolean);
{$endif}
/// performs AES-OFB encryption and decryption on whole blocks
// - may be called instead of TAESOFB when only a raw TAES is available
// - this method is thread-safe (except if padlock is used)
procedure DoBlocksOFB(const iv: TAESBlock; src, dst: pointer; blockcount: PtrUInt);
/// TRUE if the context was initialized via EncryptInit/DecryptInit
function Initialized: boolean; {$ifdef FPC}inline;{$endif}
/// return TRUE if the AES-NI instruction sets are available on this CPU
function UsesAESNI: boolean; {$ifdef HASINLINE}inline;{$endif}
/// returns the key size in bits (128/192/256)
function KeyBits: integer; {$ifdef FPC}inline;{$endif}
end;
type
/// low-level AES-GCM processing
// - implements standard AEAD (authenticated-encryption with associated-data)
// algorithm, as defined by NIST and
TAESGCMEngine = object
private
/// standard AES encryption context
// - will use AES-NI if available
actx: TAES;
/// ghash value of the Authentication Data
aad_ghv: TAESBlock;
/// ghash value of the Ciphertext
txt_ghv: TAESBlock;
/// ghash H current value
ghash_h: TAESBlock;
/// number of Authentication Data bytes processed
aad_cnt: TQWordRec;
/// number of bytes of the Ciphertext
atx_cnt: TQWordRec;
/// initial 32-bit ctr val - to be reused in Final()
y0_val: integer;
/// current 0..15 position in encryption block
blen: byte;
/// the state of this context
flags: set of (flagInitialized, flagFinalComputed, flagFlushed);
/// lookup table for fast Galois Finite Field multiplication
// - is defined as last field of the object for better code generation
gf_t4k: array[byte] of TAESBlock;
/// build the gf_t4k[] internal table - assuming set to zero by caller
procedure Make4K_Table;
/// compute a * ghash_h in Galois Finite Field 2^128
procedure gf_mul_h(var a: TAESBlock); {$ifdef FPC} inline; {$endif}
/// low-level AES-CTR encryption
procedure internal_crypt(ptp, ctp: PByte; ILen: PtrUInt);
/// low-level GCM authentication
procedure internal_auth(ctp: PByte; ILen: PtrUInt;
var ghv: TAESBlock; var gcnt: TQWordRec);
public
/// initialize the AES-GCM structure for the supplied Key
function Init(const Key; KeyBits: PtrInt): boolean;
/// start AES-GCM encryption with a given Initialization Vector
// - IV_len is in bytes use 12 for exact IV setting, otherwise the
// supplied buffer will be hashed using gf_mul_h()
function Reset(pIV: pointer; IV_len: PtrInt): boolean;
/// encrypt a buffer with AES-GCM, updating the associated authentication data
function Encrypt(ptp, ctp: Pointer; ILen: PtrInt): boolean;
/// decrypt a buffer with AES-GCM, updating the associated authentication data
// - also validate the GMAC with the supplied ptag/tlen if ptag<>nil,
// and skip the AES-CTR phase if the authentication doesn't match
function Decrypt(ctp, ptp: Pointer; ILen: PtrInt;
ptag: pointer=nil; tlen: PtrInt=0): boolean;
/// append some data to be authenticated, but not encrypted
function Add_AAD(pAAD: pointer; aLen: PtrInt): boolean;
/// finalize the AES-GCM encryption, returning the authentication tag
// - will also flush the AES context to avoid forensic issues, unless
// andDone is forced to false
function Final(out tag: TAESBlock; andDone: boolean=true): boolean;
/// flush the AES context to avoid forensic issues
// - do nothing if Final() has been already called
procedure Done;
/// single call AES-GCM encryption and authentication process
function FullEncryptAndAuthenticate(const Key; KeyBits: PtrInt;
pIV: pointer; IV_len: PtrInt; pAAD: pointer; aLen: PtrInt;
ptp, ctp: Pointer; pLen: PtrInt; out tag: TAESBlock): boolean;
/// single call AES-GCM decryption and verification process
function FullDecryptAndVerify(const Key; KeyBits: PtrInt;
pIV: pointer; IV_len: PtrInt; pAAD: pointer; aLen: PtrInt;
ctp, ptp: Pointer; pLen: PtrInt; ptag: pointer; tLen: PtrInt): boolean;
end;
/// class-reference type (metaclass) of an AES cypher/uncypher
TAESAbstractClass = class of TAESAbstract;
/// used internally by TAESAbstract to detect replay attacks
// - when EncryptPKCS7/DecryptPKCS7 are used with IVAtBeginning=true, and
// IVReplayAttackCheck property contains repCheckedIfAvailable or repMandatory
// - EncryptPKCS7 will encrypt this record (using the global shared
// AESIVCTR_KEY over AES-128) to create a random IV, as a secure
// cryptographic pseudorandom number generator (CSPRNG), nonce and ctr
// ensuring 96 bits of entropy
// - DecryptPKCS7 will decode and ensure that the IV has an increasing CTR
// - memory size matches an TAESBlock on purpose, for direct encryption
TAESIVCTR = packed record
/// 8 bytes of random value
nonce: QWord;
/// contains the crc32c hash of the block cipher mode (e.g. 'AESCFB')
// - when magic won't match (i.e. in case of mORMot revision < 3063), the
// check won't be applied in DecryptPKCS7: this security feature is
// backward compatible if IVReplayAttackCheck is repCheckedIfAvailable,
// but will fail for repMandatory
magic: cardinal;
/// an increasing counter, used to detect replay attacks
// - is set to a 32-bit random value at initialization
// - is increased by one for every EncryptPKCS7, so can be checked against
// replay attack in DecryptPKCS7, and implement a safe CSPRNG for stored IV
ctr: cardinal;
end;
/// how TAESAbstract.DecryptPKCS7 should detect replay attack
// - repNoCheck and repCheckedIfAvailable will be compatible with older
// versions of the protocol, but repMandatory will reject any encryption
// without the TAESIVCTR algorithm
TAESIVReplayAttackCheck = (repNoCheck, repCheckedIfAvailable, repMandatory);
/// handle AES cypher/uncypher with chaining
// - use any of the inherited implementation, corresponding to the chaining
// mode required - TAESECB, TAESCBC, TAESCFB, TAESOFB and TAESCTR classes to
// handle in ECB, CBC, CFB, OFB and CTR mode (including PKCS7-like padding)
TAESAbstract = class(TSynPersistent)
protected
fKeySize: cardinal;
fKeySizeBytes: cardinal;
fKey: TAESKey;
fIV: TAESBlock;
fIVCTR: TAESIVCTR;
fIVCTRState: (ctrUnknown, ctrUsed, ctrNotused);
fIVHistoryDec: THash128History;
fIVReplayAttackCheck: TAESIVReplayAttackCheck;
procedure SetIVHistory(aDepth: integer);
procedure SetIVCTR;
function DecryptPKCS7Len(var InputLen,ivsize: integer; Input: pointer;
IVAtBeginning, RaiseESynCryptoOnError: boolean): boolean;
public
/// Initialize AES context for cypher
// - first method to call before using this class
// - KeySize is in bits, i.e. 128,192,256
constructor Create(const aKey; aKeySize: cardinal); reintroduce; overload; virtual;
/// Initialize AES context for AES-128 cypher
// - first method to call before using this class
// - just a wrapper around Create(aKey,128);
constructor Create(const aKey: THash128); reintroduce; overload;
/// Initialize AES context for AES-256 cypher
// - first method to call before using this class
// - just a wrapper around Create(aKey,256);
constructor Create(const aKey: THash256); reintroduce; overload;
/// Initialize AES context for cypher, from some TAESPRNG random bytes
// - may be used to hide some sensitive information from memory, like
// CryptDataForCurrentUser but with a temporary key
constructor CreateTemp(aKeySize: cardinal);
/// Initialize AES context for cypher, from SHA-256 hash
// - here the Key is supplied as a string, and will be hashed using SHA-256
// via the SHA256Weak proprietary algorithm - to be used only for backward
// compatibility of existing code
// - consider using more secure (and more standard) CreateFromPBKDF2 instead
constructor CreateFromSha256(const aKey: RawUTF8);
/// Initialize AES context for cypher, from PBKDF2_HMAC_SHA256 derivation
// - here the Key is supplied as a string, and will be hashed using
// PBKDF2_HMAC_SHA256 with the specified salt and rounds
constructor CreateFromPBKDF2(const aKey: RawUTF8; const aSalt: RawByteString;
aRounds: Integer);
/// compute a class instance similar to this one
// - could be used to have a thread-safe re-use of a given encryption key
function Clone: TAESAbstract; virtual;
/// compute a class instance similar to this one, for performing the
// reverse encryption/decryption process
// - this default implementation calls Clone, but CFB/OFB/CTR chaining modes
// using only AES encryption (i.e. inheriting from TAESAbstractEncryptOnly)
// will return self to avoid creating two instances
// - warning: to be used only with IVAtBeginning=false
function CloneEncryptDecrypt: TAESAbstract; virtual;
/// release the used instance memory and resources
// - also fill the secret fKey buffer with zeros, for safety
destructor Destroy; override;
/// perform the AES cypher in the corresponding mode
// - when used in block chaining mode, you should have set the IV property
procedure Encrypt(BufIn, BufOut: pointer; Count: cardinal); virtual; abstract;
/// perform the AES un-cypher in the corresponding mode
// - when used in block chaining mode, you should have set the IV property
procedure Decrypt(BufIn, BufOut: pointer; Count: cardinal); virtual; abstract;
/// encrypt a memory buffer using a PKCS7 padding pattern
// - PKCS7 padding is described in RFC 5652 - it will add up to 16 bytes to
// the input buffer; note this method uses the padding only, not the whole
// PKCS#7 Cryptographic Message Syntax
// - if IVAtBeginning is TRUE, a random Initialization Vector will be computed,
// and stored at the beginning of the output binary buffer - this IV may
// contain an internal encrypted CTR, to detect any replay attack attempt,
// if IVReplayAttackCheck is set to repCheckedIfAvailable or repMandatory
function EncryptPKCS7(const Input: RawByteString; IVAtBeginning: boolean=false): RawByteString; overload;
/// decrypt a memory buffer using a PKCS7 padding pattern
// - PKCS7 padding is described in RFC 5652 - it will trim up to 16 bytes from
// the input buffer; note this method uses the padding only, not the whole
// PKCS#7 Cryptographic Message Syntax
// - if IVAtBeginning is TRUE, the Initialization Vector will be taken
// from the beginning of the input binary buffer - if IVReplayAttackCheck is
// set, this IV will be validated to contain an increasing encrypted CTR,
// and raise an ESynCrypto when a replay attack attempt is detected
// - if RaiseESynCryptoOnError=false, returns '' on any decryption error
function DecryptPKCS7(const Input: RawByteString; IVAtBeginning: boolean=false;
RaiseESynCryptoOnError: boolean=true): RawByteString; overload;
/// encrypt a memory buffer using a PKCS7 padding pattern
// - PKCS7 padding is described in RFC 5652 - it will add up to 16 bytes to
// the input buffer; note this method uses the padding only, not the whole
// PKCS#7 Cryptographic Message Syntax
// - if IVAtBeginning is TRUE, a random Initialization Vector will be computed,
// and stored at the beginning of the output binary buffer - this IV may
// contain an internal encrypted CTR, to detect any replay attack attempt,
// if IVReplayAttackCheck is set to repCheckedIfAvailable or repMandatory
function EncryptPKCS7(const Input: TBytes; IVAtBeginning: boolean=false): TBytes; overload;
/// decrypt a memory buffer using a PKCS7 padding pattern
// - PKCS7 padding is described in RFC 5652 - it will trim up to 16 bytes from
// the input buffer; note this method uses the padding only, not the whole
// PKCS#7 Cryptographic Message Syntax
// - if IVAtBeginning is TRUE, the Initialization Vector will be taken
// from the beginning of the input binary buffer - if IVReplayAttackCheck is
// set, this IV will be validated to contain an increasing encrypted CTR,
// and raise an ESynCrypto when a replay attack attempt is detected
// - if RaiseESynCryptoOnError=false, returns [] on any decryption error
function DecryptPKCS7(const Input: TBytes; IVAtBeginning: boolean=false;
RaiseESynCryptoOnError: boolean=true): TBytes; overload;
/// compute how many bytes would be needed in the output buffer, when
// encrypte using a PKCS7 padding pattern
// - could be used to pre-compute the OutputLength for EncryptPKCS7Buffer()
// - PKCS7 padding is described in RFC 5652 - it will add up to 16 bytes to
// the input buffer; note this method uses the padding only, not the whole
// PKCS#7 Cryptographic Message Syntax
function EncryptPKCS7Length(InputLen: cardinal; IVAtBeginning: boolean): cardinal;
{$ifdef HASINLINE}inline;{$endif}
/// encrypt a memory buffer using a PKCS7 padding pattern
// - PKCS7 padding is described in RFC 5652 - it will add up to 16 bytes to
// the input buffer; note this method uses the padding only, not the whole
// PKCS#7 Cryptographic Message Syntax
// - use EncryptPKCS7Length() function to compute the actual needed length
// - if IVAtBeginning is TRUE, a random Initialization Vector will be computed,
// and stored at the beginning of the output binary buffer - this IV will in
// fact contain an internal encrypted CTR, to detect any replay attack attempt
// - returns TRUE on success, FALSE if OutputLen is not correct - you should
// use EncryptPKCS7Length() to compute the exact needed number of bytes
function EncryptPKCS7Buffer(Input,Output: Pointer; InputLen,OutputLen: cardinal;
IVAtBeginning: boolean): boolean;
/// decrypt a memory buffer using a PKCS7 padding pattern
// - PKCS7 padding is described in RFC 5652 - it will trim up to 16 bytes from
// the input buffer; note this method uses the padding only, not the whole
// PKCS#7 Cryptographic Message Syntax
// - if IVAtBeginning is TRUE, the Initialization Vector will be taken
// from the beginning of the input binary buffer - this IV will in fact
// contain an internal encrypted CTR, to detect any replay attack attempt
// - if RaiseESynCryptoOnError=false, returns '' on any decryption error
function DecryptPKCS7Buffer(Input: Pointer; InputLen: integer;
IVAtBeginning: boolean; RaiseESynCryptoOnError: boolean=true): RawByteString;
/// initialize AEAD (authenticated-encryption with associated-data) nonce
// - i.e. setup 256-bit MAC computation during next Encrypt/Decrypt call
// - may be used e.g. for AES-GCM or our custom AES-CTR modes
// - default implementation, for a non AEAD protocol, returns false
function MACSetNonce(const aKey: THash256; aAssociated: pointer=nil;
aAssociatedLen: integer=0): boolean; virtual;
/// returns AEAD (authenticated-encryption with associated-data) MAC
/// - i.e. optional 256-bit MAC computation during last Encrypt/Decrypt call
// - may be used e.g. for AES-GCM or our custom AES-CTR modes
// - default implementation, for a non AEAD protocol, returns false
function MACGetLast(out aCRC: THash256): boolean; virtual;
/// validate if the computed AEAD MAC matches the expected supplied value
// - is just a wrapper around MACGetLast() and IsEqual() functions
function MACEquals(const aCRC: THash256): boolean; virtual;
/// validate if an encrypted buffer matches the stored AEAD MAC
// - expects the 256-bit MAC, as returned by MACGetLast, to be stored after
// the encrypted data
// - default implementation, for a non AEAD protocol, returns false
function MACCheckError(aEncrypted: pointer; Count: cardinal): boolean; virtual;
/// perform one step PKCS7 encryption/decryption and authentication from
// a given 256-bit key
// - returns '' on any (MAC) issue during decryption (Encrypt=false) or if
// this class does not support AEAD MAC
// - as used e.g. by CryptDataForCurrentUser()
// - do not use this abstract class method, but inherited TAESCFBCRC/TAESOFBCRC
// - will store a header with its own CRC, so detection of most invalid
// formats (e.g. from fuzzing input) will occur before any AES/MAC process
class function MACEncrypt(const Data: RawByteString; const Key: THash256;
Encrypt: boolean): RawByteString; overload;
/// perform one step PKCS7 encryption/decryption and authentication from
// a given 128-bit key
// - returns '' on any (MAC) issue during decryption (Encrypt=false) or if
// this class does not support AEAD MAC
// - do not use this abstract class method, but inherited TAESCFBCRC/TAESOFBCRC
// - will store a header with its own CRC, so detection of most invalid
// formats (e.g. from fuzzing input) will occur before any AES/MAC process
class function MACEncrypt(const Data: RawByteString; const Key: THash128;
Encrypt: boolean): RawByteString; overload;
/// perform one step PKCS7 encryption/decryption and authentication with
// the curent AES instance
// - returns '' on any (MAC) issue during decryption (Encrypt=false) or if
// this class does not support AEAD MAC
// - as used e.g. by CryptDataForCurrentUser()
// - do not use this abstract class method, but inherited TAESCFBCRC/TAESOFBCRC
// - will store a header with its own CRC, so detection of most invalid
// formats (e.g. from fuzzing input) will occur before any AES/MAC process
function MACAndCrypt(const Data: RawByteString; Encrypt: boolean): RawByteString;
/// simple wrapper able to cypher/decypher any in-memory content
// - here data variables could be text or binary
// - use StringToUTF8() to define the Key parameter from a VCL string
// - if IVAtBeginning is TRUE, a random Initialization Vector will be computed,
// and stored at the beginning of the output binary buffer
// - will use SHA256Weak() and PKCS7 padding with the current class mode
class function SimpleEncrypt(const Input,Key: RawByteString; Encrypt: boolean;
IVAtBeginning: boolean=false; RaiseESynCryptoOnError: boolean=true): RawByteString; overload;
/// simple wrapper able to cypher/decypher any in-memory content
// - here data variables could be text or binary
// - you could use e.g. THMAC_SHA256 to safely compute the Key/KeySize value
// - if IVAtBeginning is TRUE, a random Initialization Vector will be computed,
// and stored at the beginning of the output binary buffer
// - will use SHA256Weak() and PKCS7 padding with the current class mode
class function SimpleEncrypt(const Input: RawByteString; const Key;
KeySize: integer; Encrypt: boolean; IVAtBeginning: boolean=false;
RaiseESynCryptoOnError: boolean=true): RawByteString; overload;
/// simple wrapper able to cypher/decypher any file content
// - just a wrapper around SimpleEncrypt() and StringFromFile/FileFromString
// - use StringToUTF8() to define the Key parameter from a VCL string
// - if IVAtBeginning is TRUE, a random Initialization Vector will be computed,
// and stored at the beginning of the output binary buffer
// - will use SHA256Weak() and PKCS7 padding with the current class mode
class function SimpleEncryptFile(const InputFile, OutputFile: TFileName;
const Key: RawByteString; Encrypt: boolean; IVAtBeginning: boolean=false;
RaiseESynCryptoOnError: boolean=true): boolean; overload;
/// simple wrapper able to cypher/decypher any file content
// - just a wrapper around SimpleEncrypt() and StringFromFile/FileFromString
// - you could use e.g. THMAC_SHA256 to safely compute the Key/KeySize value
// - if IVAtBeginning is TRUE, a random Initialization Vector will be computed,
// and stored at the beginning of the output binary buffer
// - will use SHA256Weak() and PKCS7 padding with the current class mode
class function SimpleEncryptFile(const InputFile, Outputfile: TFileName; const Key;
KeySize: integer; Encrypt: boolean; IVAtBeginning: boolean=false;
RaiseESynCryptoOnError: boolean=true): boolean; overload;
//// returns e.g. 'aes128cfb' or '' if nil
function AlgoName: TShort16;
/// associated Key Size, in bits (i.e. 128,192,256)
property KeySize: cardinal read fKeySize;
/// associated Initialization Vector
// - all modes (except ECB) do expect an IV to be supplied for chaining,
// before any encryption or decryption is performed
// - you could also use PKCS7 encoding with IVAtBeginning=true option
property IV: TAESBlock read fIV write fIV;
/// let IV detect replay attack for EncryptPKCS7 and DecryptPKCS7
// - if IVAtBeginning=true and this property is set, EncryptPKCS7 will
// store a random IV from an internal CTR, and DecryptPKCS7 will check this
// incoming IV CTR consistency, and raise an ESynCrypto exception on failure
// - leave it to its default repNoCheck if the very same TAESAbstract
// instance is expected to be used with several sources, by which the IV CTR
// will be unsynchronized
// - security warning: by design, this is NOT cautious with CBC chaining:
// you should use it only with CFB, OFB or CTR mode, since the IV sequence
// will be predictable if you know the fixed AES private key of this unit,
// but the IV sequence features uniqueness as it is generated by a good PRNG -
// see http://crypto.stackexchange.com/q/3515
property IVReplayAttackCheck: TAESIVReplayAttackCheck
read fIVReplayAttackCheck write fIVReplayAttackCheck;
/// maintains an history of previous IV, to avoid re-play attacks
// - only useful when EncryptPKCS7/DecryptPKCS7 are used with
// IVAtBeginning=true, and IVReplayAttackCheck is left to repNoCheck
property IVHistoryDepth: integer read fIVHistoryDec.Depth write SetIVHistory;
end;
/// handle AES cypher/uncypher with chaining with out own optimized code
// - use any of the inherited implementation, corresponding to the chaining
// mode required - TAESECB, TAESCBC, TAESCFB, TAESOFB and TAESCTR classes to
// handle in ECB, CBC, CFB, OFB and CTR mode (including PKCS7-like padding)
// - this class will use AES-NI hardware instructions, if available
// - those classes are re-entrant, i.e. that you can call the Encrypt*
// or Decrypt* methods on the same instance several times
TAESAbstractSyn = class(TAESAbstract)
protected
fIn, fOut: PAESBlock;
fCV: TAESBlock;
AES: TAES;
fAESInit: (initNone, initEncrypt, initDecrypt);
procedure EncryptInit;
procedure DecryptInit;
procedure TrailerBytes(count: cardinal);
public
/// creates a new instance with the very same values
// - by design, our classes will use TAES stateless context, so this method
// will just copy the current fields to a new instance, by-passing
// the key creation step
function Clone: TAESAbstract; override;
/// release the used instance memory and resources
// - also fill the TAES instance with zeros, for safety
destructor Destroy; override;
/// perform the AES cypher in the corresponding mode, over Count bytes
// - this abstract method will set CV from fIV property, and fIn/fOut
// from BufIn/BufOut
procedure Encrypt(BufIn, BufOut: pointer; Count: cardinal); override;
/// perform the AES un-cypher in the corresponding mode
// - this abstract method will set CV from fIV property, and fIn/fOut
// from BufIn/BufOut
procedure Decrypt(BufIn, BufOut: pointer; Count: cardinal); override;
/// read-only access to the internal CV block, which may be have just been
// used by Encrypt/Decrypt methods
property CV: TAESBlock read fCV;
end;
/// handle AES cypher/uncypher without chaining (ECB)
// - this mode is known to be less secure than the others
// - IV property should be set to a fixed value to encode the trailing bytes
// of the buffer by a simple XOR - but you should better use the PKC7 pattern
// - this class will use AES-NI hardware instructions, if available, e.g.
// ! ECB128: 19.70ms in x86 optimized code, 6.97ms with AES-NI
TAESECB = class(TAESAbstractSyn)
public
/// perform the AES cypher in the ECB mode
procedure Encrypt(BufIn, BufOut: pointer; Count: cardinal); override;
/// perform the AES un-cypher in the ECB mode
procedure Decrypt(BufIn, BufOut: pointer; Count: cardinal); override;
end;
/// handle AES cypher/uncypher with Cipher-block chaining (CBC)
// - this class will use AES-NI hardware instructions, if available, e.g.
// ! CBC192: 24.91ms in x86 optimized code, 9.75ms with AES-NI
// - expect IV to be set before process, or IVAtBeginning=true
TAESCBC = class(TAESAbstractSyn)
public
/// perform the AES cypher in the CBC mode
procedure Encrypt(BufIn, BufOut: pointer; Count: cardinal); override;
/// perform the AES un-cypher in the CBC mode
procedure Decrypt(BufIn, BufOut: pointer; Count: cardinal); override;
end;
/// abstract parent class for chaining modes using only AES encryption
TAESAbstractEncryptOnly = class(TAESAbstractSyn)
public
/// Initialize AES context for cypher
// - will pre-generate the encryption key (aKeySize in bits, i.e. 128,192,256)
constructor Create(const aKey; aKeySize: cardinal); override;
/// compute a class instance similar to this one, for performing the
// reverse encryption/decryption process
// - will return self to avoid creating two instances
// - warning: to be used only with IVAtBeginning=false
function CloneEncryptDecrypt: TAESAbstract; override;
end;
/// handle AES cypher/uncypher with Cipher feedback (CFB)
// - this class will use AES-NI hardware instructions, if available, e.g.
// ! CFB128: 22.25ms in x86 optimized code, 9.29ms with AES-NI
// - expect IV to be set before process, or IVAtBeginning=true
TAESCFB = class(TAESAbstractEncryptOnly)
public
/// perform the AES cypher in the CFB mode
procedure Encrypt(BufIn, BufOut: pointer; Count: cardinal); override;
/// perform the AES un-cypher in the CFB mode
procedure Decrypt(BufIn, BufOut: pointer; Count: cardinal); override;
end;
/// handle AES cypher/uncypher with Output feedback (OFB)
// - this class will use AES-NI hardware instructions, if available, e.g.
// ! OFB256: 27.69ms in x86 optimized code, 9.94ms with AES-NI
// - expect IV to be set before process, or IVAtBeginning=true
// - TAESOFB 128/256 have an optimized asm version under x86_64 + AES_NI
TAESOFB = class(TAESAbstractEncryptOnly)
public
/// perform the AES cypher in the OFB mode
procedure Encrypt(BufIn, BufOut: pointer; Count: cardinal); override;
/// perform the AES un-cypher in the OFB mode
procedure Decrypt(BufIn, BufOut: pointer; Count: cardinal); override;
end;
/// handle AES cypher/uncypher with 64-bit Counter mode (CTR)
// - the CTR will use a counter in bytes 7..0 by default - which is safe
// but not standard - call ComposeIV() to change e.g. to NIST behavior
// - this class will use AES-NI hardware instructions, e.g.
// ! CTR256: 28.13ms in x86 optimized code, 10.63ms with AES-NI
// - expect IV to be set before process, or IVAtBeginning=true
TAESCTR = class(TAESAbstractEncryptOnly)
protected
fCTROffset, fCTROffsetMin: PtrInt;
public
/// Initialize AES context for cypher
// - will pre-generate the encryption key (aKeySize in bits, i.e. 128,192,256)
constructor Create(const aKey; aKeySize: cardinal); override;
/// defines how the IV is set and updated in CTR mode
// - default (if you don't call this method) uses a Counter in bytes 7..0
// - you can specify startup Nonce and Counter, and the Counter position
// - NonceLen + CounterLen should be 16 - otherwise it fails and returns false
function ComposeIV(Nonce, Counter: PAESBlock; NonceLen, CounterLen: integer;
LSBCounter: boolean): boolean; overload;
/// defines how the IV is set and updated in CTR mode
// - you can specify startup Nonce and Counter, and the Counter position
// - Nonce + Counter lengths should add to 16 - otherwise returns false
function ComposeIV(const Nonce, Counter: TByteDynArray; LSBCounter: boolean): boolean; overload;
/// perform the AES cypher in the CTR mode
procedure Encrypt(BufIn, BufOut: pointer; Count: cardinal); override;
/// perform the AES un-cypher in the CTR mode
procedure Decrypt(BufIn, BufOut: pointer; Count: cardinal); override;
end;
/// internal 256-bit structure used for TAESAbstractAEAD MAC storage
TAESMAC256 = record
/// the AES-encrypted MAC of the plain content
// - plain text digital signature, to perform message authentication
// and integrity
plain: THash128;
/// the plain MAC of the encrypted content
// - encrypted text digital signature, to check for errors,
// with no compromission of the plain content
encrypted: THash128;
end;
/// AEAD (authenticated-encryption with associated-data) abstract class
// - perform AES encryption and on-the-fly MAC computation, i.e. computes
// a proprietary 256-bit MAC during AES cyphering, as 128-bit CRC of the
// encrypted data and 128-bit CRC of the plain data, seeded from a Key
// - the 128-bit CRC of the plain text is then encrypted using the current AES
// engine, so returned 256-bit MAC value has cryptographic level, and ensure
// data integrity, authenticity, and check against transmission errors
TAESAbstractAEAD = class(TAESAbstractEncryptOnly)
protected
fMAC, fMACKey: TAESMAC256;
public
/// release the used instance memory and resources
// - also fill the internal internal MAC hashes with zeros, for safety
destructor Destroy; override;
/// initialize 256-bit MAC computation for next Encrypt/Decrypt call
// - initialize the internal fMACKey property, and returns true
// - only the plain text crc is seeded from aKey - encrypted message crc
// will use -1 as fixed seed, to avoid aKey compromission
// - should be set with a new MAC key value before each message, to avoid
// replay attacks (as called from TECDHEProtocol.SetKey)
function MACSetNonce(const aKey: THash256; aAssociated: pointer=nil;
aAssociatedLen: integer=0): boolean; override;
/// returns 256-bit MAC computed during last Encrypt/Decrypt call
// - encrypt the internal fMAC property value using the current AES cypher
// on the plain content and returns true; only the plain content CRC-128 is
// AES encrypted, to avoid reverse attacks against the known encrypted data
function MACGetLast(out aCRC: THash256): boolean; override;
/// validate if an encrypted buffer matches the stored MAC
// - expects the 256-bit MAC, as returned by MACGetLast, to be stored after
// the encrypted data
// - returns true if the 128-bit CRC of the encrypted text matches the
// supplied buffer, ignoring the 128-bit CRC of the plain data
// - since it is easy to forge such 128-bit CRC, it will only indicate
// that no transmission error occured, but won't be an integrity or
// authentication proof (which will need full Decrypt + MACGetLast)
// - may use any MACSetNonce() aAssociated value
function MACCheckError(aEncrypted: pointer; Count: cardinal): boolean; override;
end;
/// AEAD combination of AES with Cipher feedback (CFB) and 256-bit MAC
// - this class will use AES-NI and CRC32C hardware instructions, if available
// - expect IV to be set before process, or IVAtBeginning=true
TAESCFBCRC = class(TAESAbstractAEAD)
public
/// perform the AES cypher in the CFB mode, and compute a 256-bit MAC
procedure Encrypt(BufIn, BufOut: pointer; Count: cardinal); override;
/// perform the AES un-cypher in the CFB mode, and compute 256-bit MAC
procedure Decrypt(BufIn, BufOut: pointer; Count: cardinal); override;
end;
/// AEAD combination of AES with Output feedback (OFB) and 256-bit MAC
// - this class will use AES-NI and CRC32C hardware instructions, if available
// - expect IV to be set before process, or IVAtBeginning=true
TAESOFBCRC = class(TAESAbstractAEAD)
public
/// perform the AES cypher in the OFB mode, and compute a 256-bit MAC
procedure Encrypt(BufIn, BufOut: pointer; Count: cardinal); override;
/// perform the AES un-cypher in the OFB mode, and compute a 256-bit MAC
procedure Decrypt(BufIn, BufOut: pointer; Count: cardinal); override;
end;
/// handle AES-GCM cypher/uncypher with built-in authentication
// - implements AEAD (authenticated-encryption with associated-data) methods
// like MACEncrypt/MACCheckError
// - this class will use AES-NI hardware instructions, if available
TAESGCM = class(TAESAbstract)
protected
fAES: TAESGCMEngine;
fContext: (ctxNone,ctxEncrypt,ctxDecrypt); // used to call AES.Reset()
public
/// Initialize the AES-GCM context for cypher
// - first method to call before using this class
// - KeySize is in bits, i.e. 128,192,256
constructor Create(const aKey; aKeySize: cardinal); override;
/// creates a new instance with the very same values
// - by design, our classes will use TAESGCMEngine stateless context, so
// this method will just copy the current fields to a new instance,
// by-passing the key creation step
function Clone: TAESAbstract; override;
/// release the used instance memory and resources
// - also fill the internal TAES instance with zeros, for safety
destructor Destroy; override;
/// perform the AES-GCM cypher and authentication
procedure Encrypt(BufIn, BufOut: pointer; Count: cardinal); override;
/// perform the AES un-cypher and authentication
procedure Decrypt(BufIn, BufOut: pointer; Count: cardinal); override;
/// prepare the AES-GCM process before Encrypt/Decrypt is called
// - aKey is not used: AES-GCM has its own nonce setting algorithm, and
// the IV will be set from random value by EncryptPKCS7()
// - will just include any supplied associated data to the GMAC tag
function MACSetNonce(const aKey: THash256; aAssociated: pointer=nil;
aAssociatedLen: integer=0): boolean; override;
/// returns AEAD (authenticated-encryption with associated-data) MAC
/// - only the lower 128-bit (THash256.Lo) of aCRC is filled with the GMAC
function MACGetLast(out aCRC: THash256): boolean; override;
/// validate if an encrypted buffer matches the stored AEAD MAC
// - since AES-GCM is a one pass process, always assume the content is fine
// and returns true - we don't know the IV at this time
function MACCheckError(aEncrypted: pointer; Count: cardinal): boolean; override;
end;
{$ifdef USE_PROV_RSA_AES}
type
/// handle AES cypher/uncypher using Windows CryptoAPI and the
// official Microsoft AES Cryptographic Provider (PROV_RSA_AES)
// - see @http://msdn.microsoft.com/en-us/library/windows/desktop/aa386979
// - timing of our optimized asm versions, for small (<=8KB) block processing
// (similar to standard web pages or most typical JSON/XML content),
// benchmarked on a Core i7 notebook and compiled as Win32 platform:
// ! AES128 - ECB:79.33ms CBC:83.37ms CFB:80.75ms OFB:78.98ms CTR:80.45ms
// ! AES192 - ECB:91.16ms CBC:96.06ms CFB:96.45ms OFB:92.12ms CTR:93.38ms
// ! AES256 - ECB:103.22ms CBC:119.14ms CFB:111.59ms OFB:107.00ms CTR:110.13ms
// - timing of the same process, using CryptoAPI official PROV_RSA_AES provider:
// ! AES128 - ECB_API:102.88ms CBC_API:124.91ms
// ! AES192 - ECB_API:115.75ms CBC_API:129.95ms
// ! AES256 - ECB_API:139.50ms CBC_API:154.02ms
// - but the CryptoAPI does not supports AES-NI, whereas our classes handle it,
// with a huge speed benefit
// - under Win64, the official CryptoAPI is faster than our PUREPASCAL version,
// and the Win32 version of CryptoAPI itself, but slower than our AES-NI code
// ! AES128 - ECB:107.95ms CBC:112.65ms CFB:109.62ms OFB:107.23ms CTR:109.42ms
// ! AES192 - ECB:130.30ms CBC:133.04ms CFB:128.78ms OFB:127.25ms CTR:130.22ms
// ! AES256 - ECB:145.33ms CBC:147.01ms CFB:148.36ms OFB:145.96ms CTR:149.67ms
// ! AES128 - ECB_API:89.64ms CBC_API:100.84ms
// ! AES192 - ECB_API:99.05ms CBC_API:105.85ms
// ! AES256 - ECB_API:107.11ms CBC_API:118.04ms
// - in practice, you could forget about using the CryptoAPI, unless you are
// required to do so, for legal/corporate reasons
TAESAbstract_API = class(TAESAbstract)
protected
fKeyHeader: packed record
bType: byte;
bVersion: byte;
reserved: word;
aiKeyAlg: cardinal;
dwKeyLength: cardinal;
end;
fKeyHeaderKey: TAESKey; // should be just after fKeyHeader record
fKeyCryptoAPI: pointer;
fInternalMode: cardinal;
procedure InternalSetMode; virtual; abstract;
procedure EncryptDecrypt(BufIn, BufOut: pointer; Count: cardinal; DoEncrypt: boolean);
public
/// Initialize AES context for cypher
// - first method to call before using this class
// - KeySize is in bits, i.e. 128,192,256
constructor Create(const aKey; aKeySize: cardinal); override;
/// release the AES execution context
destructor Destroy; override;
/// perform the AES cypher in the ECB mode
// - if Count is not a multiple of a 16 bytes block, the IV will be used
// to XOR the trailing bytes - so it won't be compatible with our
// TAESAbstractSyn classes: you should better use PKC7 padding instead
procedure Encrypt(BufIn, BufOut: pointer; Count: cardinal); override;
/// perform the AES un-cypher in the ECB mode
// - if Count is not a multiple of a 16 bytes block, the IV will be used
// to XOR the trailing bytes - so it won't be compatible with our
// TAESAbstractSyn classes: you should better use PKC7 padding instead
procedure Decrypt(BufIn, BufOut: pointer; Count: cardinal); override;
end;
/// handle AES cypher/uncypher without chaining (ECB) using Windows CryptoAPI
TAESECB_API = class(TAESAbstract_API)
protected
/// will set fInternalMode := CRYPT_MODE_ECB
procedure InternalSetMode; override;
end;
/// handle AES cypher/uncypher Cipher-block chaining (CBC) using Windows CryptoAPI
TAESCBC_API = class(TAESAbstract_API)
protected