Repository navigation
Expand file tree
/
Copy pathmormot.crypt.ecc.pas
More file actions
6624 lines (6149 loc) · 239 KB
/
Copy pathmormot.crypt.ecc.pas
File metadata and controls
6624 lines (6149 loc) · 239 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
/// Framework Core High-Level Public-Key Elliptic-Curve Cryptography
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.crypt.ecc;
{
*****************************************************************************
Certificate-based Public Key Cryptography Classes
- High-Level Certificate-based Public Key Cryptography
- HMAC-CRC32C and HMAC-CRC256C Message Integrity Algorithms
- IProtocol Implemented using our Public Key Cryptography
- Registration of our ECC Engine to the TCryptAsym/TCryptCert Factories
*****************************************************************************
Legal Notice: as stated by our LICENSE.md terms, make sure that you comply
to any restriction about the use of cryptographic software in your country.
}
interface
{$I ..\mormot.defines.inc}
uses
classes,
sysutils,
mormot.core.base,
mormot.core.os,
mormot.core.os.security,
mormot.core.unicode,
mormot.core.text,
mormot.core.buffers,
mormot.core.data,
mormot.core.datetime,
mormot.core.variants,
mormot.core.rtti,
mormot.core.json,
mormot.core.fmt,
mormot.core.search, // for EccKeyFileFind()
mormot.crypt.core,
mormot.crypt.secure,
mormot.crypt.ecc256r1;
{ ***************** High-Level Certificate-based Public Key Cryptography }
type
/// the known algorithms implemented in ECIES encryption
// - supports AES 256-bit encryption with safe block modes (weack ECB mode
// is not available) - or AES 128-bit if needed (e.g. for regulatory issues)
// - safe HMAC SHA-256 is used as MAC algorithm, or AES-GCM
// - optional SynLZ compression can be enabled
TEciesAlgo = (
ecaUnknown,
ecaPBKDF2_HMAC_SHA256_AES256_CFB,
ecaPBKDF2_HMAC_SHA256_AES256_CBC,
ecaPBKDF2_HMAC_SHA256_AES256_OFB,
ecaPBKDF2_HMAC_SHA256_AES256_CTR,
ecaPBKDF2_HMAC_SHA256_AES256_CFB_SYNLZ,
ecaPBKDF2_HMAC_SHA256_AES256_CBC_SYNLZ,
ecaPBKDF2_HMAC_SHA256_AES256_OFB_SYNLZ,
ecaPBKDF2_HMAC_SHA256_AES256_CTR_SYNLZ,
ecaPBKDF2_HMAC_SHA256_AES128_CFB_SYNLZ,
ecaPBKDF2_HMAC_SHA256_AES128_CBC_SYNLZ,
ecaPBKDF2_HMAC_SHA256_AES128_OFB_SYNLZ,
ecaPBKDF2_HMAC_SHA256_AES128_CTR_SYNLZ,
ecaPBKDF2_HMAC_SHA256_AES128_CFB,
ecaPBKDF2_HMAC_SHA256_AES128_CBC,
ecaPBKDF2_HMAC_SHA256_AES128_OFB,
ecaPBKDF2_HMAC_SHA256_AES128_CTR,
ecaPBKDF2_AES128_GCM,
ecaPBKDF2_AES256_GCM,
ecaPBKDF2_AES128_GCM_SYNLZ,
ecaPBKDF2_AES256_GCM_SYNLZ,
ecaPBKDF2_AES128_CTC,
ecaPBKDF2_AES256_CTC,
ecaPBKDF2_AES128_CTC_SYNLZ,
ecaPBKDF2_AES256_CTC_SYNLZ);
/// binary header of a .synecc file, encrypted via ECC secp256r1
// - as generated by TEccCertificate.Encrypt/EncryptFile, and decoded by
// TEccCertificateSecret.Decrypt
// - a sign-then-encrypt pattern may have been implemented for additional safety
TEciesHeader = packed record
/// contains 'SynEccEncrypted'#26
// - so every .synecc file starts with those characters as signature
magic: THash128;
/// TEccCertificate.Issuer of the recipient public key used for encryption
// - is either geniune random bytes, or some Baudot-encoded text
rec: TEccCertificateIssuer;
/// TEccCertificate.Serial of the recipient public key used for encryption
recid: TEccCertificateID;
/// the size of the plain content (may be compressed before encryption)
size: cardinal;
/// when this encryption was performed
date: TEccDate;
/// optional (local) timestamp, in Unix seconds since 1970, of the source file
unixts: cardinal;
/// actual encryption algorithm used
algo: TEciesAlgo;
/// the genuine random public key used for encryption
rndpub: TEccPublicKey;
/// optional ECDSA secp256r1 digital signature of the plain content
sign: TEccSignatureCertifiedContent;
/// the Message Authentication Code of the encrypted content
hmac: THash256;
/// a crc32c hash of the header (excluding this field)
crc: cardinal;
end;
/// points to the binary header of a .synecc encrypted file
PEciesHeader = ^TEciesHeader;
function ToText(algo: TEciesAlgo): PShortString; overload;
/// validate the binary header of a .synecc file buffer, encrypted via ECC secp256r1
// - will check against the expected layout, and values stored (e.g. crc)
// - returns true if head is a valid .synecc header, false otherwise
function EciesHeader(const head: TEciesHeader): boolean; overload;
/// extract the binary header of a .synecc file buffer, encrypted via ECC secp256r1
// - match the format generated by TEccCertificate.Encrypt/EncryptFile
// - returns true on success, false otherwise
function EciesHeader(const encrypted: RawByteString;
out head: TEciesHeader): boolean; overload;
/// extract the binary header of a .synecc file, encrypted via ECC secp256r1
// - match the format generated by TEccCertificate.Encrypt/EncryptFile
// - returns true on success, false otherwise
// - if rawencryptedfile is specified, will also create such a file with the
// raw encrypted content (i.e. excluding the encryptedfile header)
function EciesHeaderFile(const encryptedfile: TFileName; out head: TEciesHeader;
const rawencryptedfile: TFileName = ''): boolean;
/// convert the binary header of a .synecc file buffer into a JSON object
// - returns '' if the header is not a valid .synecc file
function EciesHeaderText(const head: TEciesHeader): RawUtf8; overload;
/// convert the header of a .synecc file into a JSON object
// - returns '' if the header is not a valid .synecc file
// - if rawencryptedfile is specified, will also create such a file with the
// raw encrypted content (i.e. excluding the encryptedfile header)
function EciesHeaderText(const encryptedfile: TFileName;
const rawencryptedfile: TFileName = ''): RawUtf8; overload;
/// encrypt a message using a ECC secp256r1 public key
// - similar to EVP_PKEY.RsaSeal, as a cut-down version of our ECIES algorithm
// - store the ephemeral public key as output trailer, followed by ciphered data
// - ephemeral secret and IV are SHA-3 derivated from safe ECDH shared secret
function EciesSeal(aes: TAesAbstractClass; aesbits: integer;
const pubkey: TEccPublicKey; const msg: RawByteString): RawByteString; overload;
/// decrypt a message using a ECC secp256r1 private key
// - similar to EVP_PKEY.RsaOpen, as a cut-down version of our ECIES algorithm
// - expects the ephemeral public key as input trailer, followed by ciphered data
// - ephemeral secret and IV are SHA-3 derivated from safe ECDH shared secret
function EciesOpen(aes: TAesAbstractClass; aesbits: integer;
const privkey: TEccPrivateKey; const msg: RawByteString): RawByteString; overload;
/// encrypt a message using a ECC secp256r1 public key
function EciesSeal(const cipher: RawUtf8; const pubkey: TEccPublicKey;
const msg: RawByteString): RawByteString; overload;
/// decrypt a message using a ECC secp256r1 private key
function EciesOpen(const cipher: RawUtf8; const privkey: TEccPrivateKey;
const msg: RawByteString): RawByteString; overload;
const
/// how many PBKDF2 rounds are performed by default for password derivation
// - this value is high enough to circumvent most brute force attacks
// - don't change this default value, unless you would break some expecations
DEFAULT_ECCROUNDS = 60000;
type
/// exception class associated with this mormot.crypt.ecc unit
EEccException = class(ESynException);
TEccSignatureCertified = class;
/// a public certificate using ECC secp256r1 cryptography
// - implements a custom binary format, with validation period, and chaining
// - could be used for safe data signing, and authentication
// - in fact, Base64 published property is enough to persist this instance:
// but consider also ToBase64/FromBase64/LoadFromStream/SaveToStream methods
TEccCertificate = class(TSynPersistent)
protected
fContent: TEccCertificateContent;
fStoreOnlyPublicKey: boolean;
fMaxVersion: byte;
fUncompressed: TEccPublicKeyUncompressed; // =fContent.Head.Signed.PublicKey
fUncompressedP: PEccPublicKeyUncompressed;
function GetAuthorityIssuer: RawUtf8;
{$ifdef HASINLINE} inline; {$endif}
function GetAuthoritySerial: RawUtf8;
{$ifdef HASINLINE} inline; {$endif}
function GetIssueDate: RawUtf8;
{$ifdef HASINLINE} inline; {$endif}
function GetIssuer: RawUtf8;
{$ifdef HASINLINE} inline; {$endif}
function GetSerial: RawUtf8;
{$ifdef HASINLINE} inline; {$endif}
function GetValidityEnd: RawUtf8;
{$ifdef HASINLINE} inline; {$endif}
function GetValidityStart: RawUtf8;
{$ifdef HASINLINE} inline; {$endif}
function GetUsage: TCryptCertUsages;
{$ifdef HASINLINE} inline; {$endif}
function GetSubject: RawUtf8;
{$ifdef HASINLINE} inline; {$endif}
function GetIsSelfSigned: boolean;
{$ifdef HASINLINE} inline; {$endif}
procedure SetBase64(const base64: RawUtf8);
{$ifdef HASINLINE} inline; {$endif}
// do nothing by default but TEccCertificateSecret will include private key
function AppendLoad(const data: RawByteString): boolean; virtual;
function AppendSave: RawByteString; virtual;
public
/// initialize this certificate
constructor Create; override;
/// initialize this certificate with an explicit maximum version support
constructor CreateVersion(MaxVers: integer);
/// initialize this certificate from a supplied Base64 encoded binary
// - will raise an EEccException if the supplied base64 is incorrect
constructor CreateFromBase64(const base64: RawUtf8); virtual;
/// initialize this certificate from a set of potential inputs
// - will first search from a .public file name, Base64 encoded binary,
// or a serial number which be used to search for a local .public file
// (as located by EccKeyFileFind)
// - will raise an EEccException if no supplied media is correct
constructor CreateFromAuth(const AuthPubKey: TFileName; const AuthBase64,
AuthSerial: RawUtf8); virtual;
/// the certification information, digitaly signed in the Signature field
property Signed: TEccCertificateSigned
read fContent.Head.Signed;
/// SHA-256 + ECDSA secp256r1 signature of the Certificate record
property Signature: TEccSignature
read fContent.Head.Signature;
/// persist the certificate as some binary
// - will use SaveToStream serialization, with optional StoreOnlyPublicKey
function SaveToBinary(PublicKeyOnly: boolean = false): RawByteString;
/// persist the certificate as some Base64 encoded binary
// - will use SaveToStream serialization
// - see PublicToBase64 to exclude the private key from a
// TEccCertificateSecret instance
function ToBase64: RawUtf8;
/// persist only the public certificate as some Base64 encoded binary
// - will follow TEccCertificate.SaveToStream/ToBase64 serialization,
// even when called from a TEccCertificateSecret instance
// - could be used to safely publish the public information of a newly
// created certificate
function PublicToBase64: RawUtf8;
/// retrieve the certificate from some Base64 encoded binary
// - will use LoadFromStream serialization
// - returns true on success, false otherwise
function FromBase64(const base64: RawUtf8): boolean;
/// retrieve the certificate from its JSON object serialization
// - will use LoadFromStream format from a "Base64": field
// - returns true on success, false otherwise
function FromJson(const json: RawUtf8): boolean;
/// retrieve the certificate from some binary
// - will use LoadFromStream serialization, so the SaveToBinary format
// - returns true on success, false otherwise
function LoadFromBinary(const binary: RawByteString): boolean;
/// retrieve the certificate from the "Base64": JSON entry of a .public file
// - will use FromBase64/LoadFromStream serialization
// - returns true on success, false otherwise
function FromFile(const filename: TFileName): boolean;
/// retrieve the certificate from a set of potential inputs
// - will first search from a .public file name, Base64 encoded binary,
// or a serial number which be used to search for a local .public file in
// the current folder or EccKeyFileFolder (as located by EccKeyFileFind)
// - returns true on success, false otherwise
function FromAuth(const AuthPubKey: TFileName; const AuthBase64,
AuthSerial: RawUtf8): boolean;
/// compare all fields of two Certificates
// - don't compare the private key for inherited TEccCertificateSecret
function IsEqual(another: TEccCertificate): boolean;
/// persist the certificate as some binary
// - returns true on success (i.e. this class stores a certificate),
// false otherwise
function SaveToStream(Stream: TStream): boolean;
/// retrieve the certificate from some Base64 encoded binary
// - returns true on success, false otherwise
function LoadFromStream(Stream: TStream): boolean;
/// fast check of the binary buffer storage of this certificate
// - ensure Content.CRC has the expected value, using FNV-1a checksum
// - does not validate the certificate against the certificates chain, nor
// perform any ECC signature: use TEccCertificateChain.IsValid instead
function CheckCRC: boolean;
/// use this Certificate as Authority to verify an ECC digital signature
function Verify(const hash: THash256;
const Signature: TEccSignatureCertifiedContent;
TimeUtc: TDateTime = 0): TEccValidity;
/// verify the certificate signature using the given Authority public key
function VerifyCertificate(Authority: TEccCertificate;
TimeUtc: TDateTime = 0): TEccValidity;
/// encrypt using the ECIES scheme, using this public certificate as key,
// via AES-256-CFB/PKCS7 overPbkdf2HmacSha256, and HmacSha256
// - returns the encrypted content, in the .synecc optimized format
// - optional salt information used for PBKDF2 or HMAC can be customized
// - ecaUnknown algorithm will use either ecaPBKDF2_HMAC_SHA256_AES256_CFB
// or ecaPBKDF2_HMAC_SHA256_AES256_CFB_SYNLZ depending if the supplied
// contain is compressible or not - but you may force another algorithm
// - you can optionally associate an ECDSA secp256r1 digital signature,
// and a timestamp which may be used when re-creating a decyphered file
// - use TEccCertificateSecret.Decrypt to uncypher the resulting content
function Encrypt(const Plain: RawByteString;
Signature: TEccSignatureCertified = nil; FileDateTime: TDateTime = 0;
const KDFSalt: RawUtf8 = 'salt'; KDFRounds: integer = DEFAULT_ECCROUNDS;
const MACSalt: RawUtf8 = 'hmac'; MACRounds: integer = 100;
Algo: TEciesAlgo = ecaUnknown): RawByteString;
/// encrypt a file using the ECIES scheme, using this public certificate as
// key,via AES-256-CFB/PKCS7 overPbkdf2HmacSha256, and HmacSha256
// - by default, will create a FileToCrypt.synecc encrypted file
// - ecaUnknown algorithm will use either ecaPBKDF2_HMAC_SHA256_AES256_CFB
// or ecaPBKDF2_HMAC_SHA256_AES256_CFB_SYNLZ depending if the supplied
// contain is compressible or not - but you may force another algorithm
// - any available .sign ECDSA secp256r1 digital signature file will be
// recognized and embedded to the resulting .synecc content
// - optional salt information used for PBKDF2 can be customized, to lock
// the encryted file with the supplied password
function EncryptFile(const FileToCrypt: TFileName;
const DestFile: TFileName = ''; const Salt: RawUtf8 = 'salt';
SaltRounds: integer = DEFAULT_ECCROUNDS; Algo: TEciesAlgo = ecaUnknown;
IncludeSignFile: boolean = true): boolean;
/// encrypt some message using the ECDH/SHA3 EciesSeal() pattern
// - so is not compatible with TEccCertificate.Encrypt() but with
// ICryptCert.Encrypt and TEccCertificateSecret.DecryptMessage
function EncryptMessage(const Plain: RawByteString;
const Cipher: RawUtf8 = 'aes-128-ctr'): RawByteString;
/// returns a TDocVariant object of all published properties of this instance
// - excludes the Base64 property content if withBase64 is set to false
function ToVariant(withBase64: boolean = true): variant;
/// save the public key as a JSON content
// - i.e. like the ToFile() .public json file
function ToJson(withBase64: boolean = true): RawUtf8;
/// save the public key as a .public json file
// - i.e. a json containing all published properties of this instance
// - persist ToVariant() as an human-readable JSON file
function ToFile(const filename: TFileName;
fmt: TTextWriterJsonFormat = jsonHumanReadable): boolean;
/// compute the hexadecimal fingerprint of this Certificate
// - is the hash of its certificate and public key binary serialization
function GetDigest(Algo: THashAlgo): RawUtf8;
/// the maximum storage version allowed for this Certificate
// - is 1 by default, but could be set e.g. to 2 to enable long Subject and
// Usage fields
property MaxVersion: byte
read fMaxVersion write fMaxVersion;
/// the CSV-encoded subjects of this certificate
// - stored in Issuer on V1 format, in a separated field on V2 format
property Subject: RawUtf8
read GetSubject;
/// low-level access to the ECC secp256r1 cryptography binary buffer
// - you should not use this property, but other methods
property Content: TEccCertificateContent
read fContent write fContent;
published
/// the TEccCertificate format version
// - currently equals 1
property Version: word
read fContent.Head.Version;
/// the genuine identifier of this certificate, as hexadecimal text
property Serial: RawUtf8
read GetSerial;
/// identify the certificate issuer, as text
property Issuer: RawUtf8
read GetIssuer;
/// when this certificate was generated, as ISO-8601 text
property IssueDate: RawUtf8
read GetIssueDate;
/// valid not before this date, as ISO-8601 text
property ValidityStart: RawUtf8
read GetValidityStart;
/// valid not after this date, as ISO-8601 text
property ValidityEnd: RawUtf8
read GetValidityEnd;
/// hexadecimal text of the authority certificate identifier used for signing
property AuthoritySerial: RawUtf8
read GetAuthoritySerial;
/// identify the authoritify issuer used for signing, as text
property AuthorityIssuer: RawUtf8
read GetAuthorityIssuer;
/// the allowed usages of this certificate
// - only encoded with V2 format, so not published as JSON property
// - V1 would set CU_ALL = 65335 which won't be serialized
property Usage: TCryptCertUsages
read GetUsage default CU_ALL;
/// if this certificate has been signed by itself
// - a self-signed certificate will have its AuthoritySerial/AuthorityIssuer
// fields matching Serial/Issuer, and should be used as "root" certificates
property IsSelfSigned: boolean
read GetIsSelfSigned;
/// Base64 encoded text of the whole certificate binary information
// - only the public part of the certificate will be shown: any private key
// of a TEccCertificateSecret instance would be trimmed
property Base64: RawUtf8
read PublicToBase64 write SetBase64;
end;
PEccCertificate = ^TEccCertificate;
/// used to store a list of TEccCertificate instances
// - e.g. in TEccCertificateChain.Items
TEccCertificateObjArray = array of TEccCertificate;
/// a public/private certificate using ECC secp256r1 cryptography
// - will store TEccCertificate public and associated private secret key
// - implements a custom binary format, with validation period, and chaining
// - could be used for safe data signing via SignToBase64/SignFile, and
// authentication / key derivation
// - allows optional anti-forensic diffusion during storage via AFSplitStripes
TEccCertificateSecret = class(TEccCertificate)
protected
fPrivateKey: TEccPrivateKey;
fAFSplitStripes: integer;
// include the private key, with AFSplitStripes, to the output stream
function AppendLoad(const data: RawByteString): boolean; override;
function AppendSave: RawByteString; override;
public
/// generate a new certificate, signed using the supplied Authority
// - if Authority is nil, will generate a self-signed certificate
// - the supplied Issuer name would be stored using AsciiToBaudot(),
// truncated to the Issuer buffer size, i.e. 16 bytes - if Issuer is '',
// Random128() will be used
// - you may specify some validity time range, if needed
// - default ParanoidVerify=true will validate the certificate digital
// signature via a call Ecc256r1Verify() to ensure its usefulness
// - warning: signature would take around 1 ms under a 32-bit compiler
constructor CreateNew(Authority: TEccCertificateSecret;
const IssuerText: RawUtf8 = ''; ExpirationDays: integer = 0;
StartDate: TDateTime = 0; ParanoidVerify: boolean = true;
Usage: TCryptCertUsages = CU_ALL; const
Subjects: RawUtf8 = ''; MaxVers: byte = 1);
/// create a certificate with its private secret key from a password-protected
// secure binary buffer
// - perform all reverse steps from SaveToSecureBinary() method
// - will raise an EEccException if the supplied Binary is incorrect
constructor CreateFromSecureBinary(const Binary: RawByteString;
const PassWord: RawUtf8; Pbkdf2Round: integer = DEFAULT_ECCROUNDS;
Aes: TAesAbstractClass = nil); overload;
/// create a certificate with its private secret key from a password-protected
// secure binary buffer
// - may be used on a constant array in executable, created via SaveToSource()
// - perform all reverse steps from SaveToSecureBinary() method
// - will raise an EEccException if the supplied Binary is incorrect
constructor CreateFromSecureBinary(Data: pointer; Len: integer;
const PassWord: RawUtf8; Pbkdf2Round: integer = DEFAULT_ECCROUNDS;
Aes: TAesAbstractClass = nil); overload;
/// create a certificate with its private secret key from an encrypted
// secure .private binary file and its associated password
// - perform all reverse steps from SaveToSecureFile() method
// - will raise an EEccException if the supplied file is incorrect
constructor CreateFromSecureFile(const FileName: TFileName;
const PassWord: RawUtf8; Pbkdf2Round: integer = DEFAULT_ECCROUNDS;
Aes: TAesAbstractClass = nil); overload;
/// create a certificate with its private secret key from an encrypted
// secure .private binary file stored in a given folder
// - overloaded constructor retrieving the file directly from its folder
// - perform all reverse steps from SaveToSecureFile() method
// - will raise an EEccException if the supplied file is incorrect
constructor CreateFromSecureFile(const FolderName: TFileName;
const Serial, PassWord: RawUtf8; Pbkdf2Round: integer = DEFAULT_ECCROUNDS;
Aes: TAesAbstractClass = nil); overload;
/// create a certificate with its private secret key from an existing
// plain TEccCertificate information and an optional private key binary
// - raise EEccException if EccPrivateKey does not match the Cert public key
// - FreeCert=true would call Cert.Free once done, e.g. to replace it
constructor CreateFrom(Cert: TEccCertificate; EccPrivateKey: PEccPrivateKey;
FreeCert: boolean = false);
/// finalize the instance, and safe erase fPrivateKey stored buffer
destructor Destroy; override;
/// returns TRUE if the private secret key is not filled with zeros
function HasSecret: boolean;
/// computes the 'Serial.private' file name of this certificate
// - as used by SaveToSecureFile()
function SaveToSecureFileName(FileNumber: integer = 0): TFileName;
/// backup the private secret key into an encrypted .private binary file
// - you should keep all your private keys in a safe dedicated folder
// - filename will be the certificate hexadecimal as 'Serial.private'
// - will use anti-forensic diffusion of the private key (64 stripes = 2KB)
// - then AES-256-CFB encryption (or the one specified in AES parameter) will
// be performed fromPbkdf2HmacSha256 derivation of an user-supplied password
function SaveToSecureFile(const PassWord: RawUtf8;
const DestFolder: TFileName; AFStripes: integer = 64;
Pbkdf2Round: integer = DEFAULT_ECCROUNDS; Aes: TAesAbstractClass = nil;
NoHeader: boolean = false): boolean;
/// backup the private secret key into several encrypted -###.private binary files
// - secret sharing can be used to store keys at many different places, e.g.
// on several local or remote drives, and therefore enhance privacy and safety
// - it will use anti-forensic diffusion of the private key to distribute it
// into pieces, in a manner that a subset of files can not regenerate the key:
// as a result, a compromission of one sub-file won't affect the secret key
// - filename will be the certificate hexadecimal as 'Serial-###.private'
// - AES-256-CFB encryption (or the one specified in AES parameter) will be
// performed fromPbkdf2HmacSha256 derivation of an user-supplied password
function SaveToSecureFiles(const PassWord: RawUtf8;
const DestFolder: TFileName; DestFileCount: integer;
AFStripes: integer = 64; Pbkdf2Round: integer = DEFAULT_ECCROUNDS;
Aes: TAesAbstractClass = nil; NoHeader: boolean = false): boolean;
/// read a private secret key from an encrypted .private binary file
// - perform all reverse steps from SaveToSecureFile() method
// - returns TRUE on success, FALSE otherwise
function LoadFromSecureFile(const FileName: TFileName;
const PassWord: RawUtf8; Pbkdf2Round: integer = DEFAULT_ECCROUNDS;
Aes: TAesAbstractClass = nil): boolean;
/// backup the private secret key into an encrypted secure binary buffer
// - you should keep all your private keys in a safe place
// - will use anti-forensic diffusion of the private key (64 stripes = 2KB)
// - then AES-256-CFB encryption (or the one specified in AES parameter) will
// be performed fromPbkdf2HmacSha256 derivation of an user-supplied password
function SaveToSecureBinary(const PassWord: RawUtf8; AFStripes: integer = 64;
Pbkdf2Round: integer = DEFAULT_ECCROUNDS; Aes: TAesAbstractClass = nil;
NoHeader: boolean = false): RawByteString;
/// backup the private secret key into an encrypted source code constant
// - may be used to integrate some private keys within an executable
// - if ConstName='', _HEXASERIAL will be used, from 24 first chars of Serial
// - the password may also be included as ConstName_PASS associated constant,
// and as ConstName_CYPH in TObjectWithPassword/TEccCertificateSecretSetting
// encrypted format
function SaveToSource(const ConstName, Comment, PassWord: RawUtf8;
IncludePassword: boolean = true; AFStripes: integer = 0;
Pbkdf2Round: integer = 100; Aes: TAesAbstractClass = nil;
IncludeRaw: boolean = true; LF: TLineFeed = lfSystem): RawUtf8;
/// read a private secret key from an encrypted secure binary buffer
// - perform all reverse steps from SaveToSecureBinary() method
// - returns TRUE on success, FALSE otherwise
function LoadFromSecureBinary(const Binary: RawByteString;
const PassWord: RawUtf8; Pbkdf2Round: integer = DEFAULT_ECCROUNDS;
Aes: TAesAbstractClass = nil): boolean; overload;
/// read a private secret key from an encrypted secure binary buffer
// - perform all reverse steps from SaveToSecureBinary() method
// - returns TRUE on success, FALSE otherwise
function LoadFromSecureBinary(Data: pointer; Len: integer;
const PassWord: RawUtf8; Pbkdf2Round: integer = DEFAULT_ECCROUNDS;
Aes: TAesAbstractClass = nil): boolean; overload;
public
/// compute a Base64 encoded signature of some digital content
// - memory buffer will be hashed using SHA-256, then will be signed using
// ECDSA over the private secret key of this certificate instance
// - you could later on verify this text signature according to the public
// key of this certificate, calling TEccCertificateChain.IsSigned()
// - create internally a temporary TEccSignatureCertified instance
function SignToBase64(Data: pointer; Len: integer): RawUtf8; overload;
/// compute a Base64 encoded signature of some digital content hash
// - signature will be certified by private secret key of this instance
// - you could later on verify this text signature according to the public
// key of this certificate, calling TEccCertificateChain.IsSigned()
// - supplied hash is likely to be from SHA-256, but could be e.g. crc256c
// - create internally a temporary TEccSignatureCertified instance
function SignToBase64(const Hash: THash256): RawUtf8; overload;
/// compute a binary encoded signature of some digital content
function SignToBinary(Data: pointer; Len: integer): RawByteString; overload;
/// compute a Binary encoded signature of some digital content hash
function SignToBinary(const Hash: THash256): RawByteString; overload;
/// compute a .sign digital signature of any file
// - SHA-256/ECDSA digital signature is included in a JSON document
// - you can set some additional metadata information for the "meta": field
// - will raise an EEccException if FileToSign does not exist
// - returns the .sign file name, which is in fact FileToSign+'.sign'
// - use TEccSignatureCertifiedFile class to load and validate such files
function SignFile(const FileToSign: TFileName;
const MetaNameValuePairs: array of const): TFileName;
/// digital sign another certificate content
// - as used e.g. by CreateNew(Authority) or TCryptCertInternal.Sign()
// - if self is nil, Dest will be self-signed
procedure SignCertificate(Dest: TEccCertificate;
ParanoidVerify: boolean = false);
/// decrypt using the ECIES scheme, using this private certificate as key,
// via AES-256-CFB/PKCS7 overPbkdf2HmacSha256, and HmacSha256
// - expects TEccCertificate.Crypt() cyphered content with its public key
// - returns the decrypted content, or '' in case of failure
// - optional shared information used for PBKDF2 or HMAC can be customized
// - optionally, you can retrieve the sign-then-encrypt ECDSA secp256r1
// signature and metadata stored in the header (to be checked via
// TEccCertificateChain.IsSigned method), and/or the associated file timestamp
function Decrypt(const Encrypted: RawByteString;
out Decrypted: RawByteString; Signature: PEccSignatureCertifiedContent = nil;
MetaData: PRawJson = nil; FileDateTime: PDateTime = nil;
const KDFSalt: RawUtf8 = 'salt'; KDFRounds: integer = DEFAULT_ECCROUNDS;
const MACSalt: RawUtf8 = 'hmac'; MACRounds: integer = 100): TEccDecrypt;
/// decrypt using the ECIES scheme, using this private certificate as key,
/// decrypt a file using the ECIES scheme, using this private certificate as
// key, via AES-256-CFB/PKCS7 overPbkdf2HmacSha256, and HmacSha256
// - makes the reverse operation of TEccCertificate.EncryptFile method
// - by default, will erase the (.synecc) extension to FileToDecrypt name
// - optional salt information used for PBKDF2 can be customized, to unlock
// the encryted file with the supplied password
// - optionally, you can retrieve the sign-then-encrypt ECDSA secp256r1
// signature stored in the header for TEccCertificateChain.IsSigned() in
// supplied Signature^ and MetaData^ values
function DecryptFile(const FileToDecrypt: TFileName;
const DestFile: TFileName = ''; const Salt: RawUtf8 = 'salt';
SaltRounds: integer = DEFAULT_ECCROUNDS;
Signature: PEccSignatureCertifiedContent = nil;
MetaData: PRawJson = nil): TEccDecrypt;
/// decrypt some message using the ECDH/SHA3 EciesOpen() pattern
// - so is not compatible with TEccCertificateSecret.Decrypt() but with
// ICryptCert.Decrypt and TEccCertificate.EncryptMessage
function DecryptMessage(const Encrypted: RawByteString;
const Cipher: RawUtf8 = 'aes-128-ctr'): RawByteString;
public
/// how many anti-forensic diffusion stripes are used for private key storage
// - default is 0, meaning no diffusion, i.e. 32 bytes of storage space
// - you may set e.g. to 32 to activate safe diffusion to 1KB of storage
// for ToBase64/SaveToStream methods
// - is modified temporarly by SaveToSecure() method
property AFSplitStripes: integer
read fAFSplitStripes;
/// disable private secret key storage in SaveToStream()
// - default is false, i.e. the private secret key will be serialized
// - you may set TRUE here so that SaveToStream() would store only the
// public certificate, as expected by a TEccCertificate class
// - is used e.g. by PublicToBase64 method to trim the private information
property StoreOnlyPublicKey: boolean
read fStoreOnlyPublicKey write fStoreOnlyPublicKey;
/// read access to the low-level stored private key
property PrivateKey: TEccPrivateKey
read fPrivateKey;
end;
/// store settings pointing to a local .private file containing a secret key
// - following TEccCertificateSecret secure binary file format
// - you may use "ECC infocrypt" command to retrieve SaveToSource constants
TEccCertificateSecretSetting = class(TObjectWithPassword)
protected
fSerial: RawUtf8;
fFileName: TFileName;
fPasswordRounds: integer;
public
/// initialize the settings with default values
constructor Create; override;
/// generate a TEccCertificateSecret instance corresponding to the settings
// - is a wrapper around TEccCertificateSecret.CreateFromSecureFile
// - will read the FileName file (if supplied), or search for the
// <Serial>.private file in the supplied folder otherwise, then
// use associated Password/PasswordRounds values to uncypher it
// - returns nil if Serial and FileName are '', or raise an exception
// on unexpected error
// - caller is responsible of freeing the returned class instance
function CertificateSecret(const FolderName: TFileName): TEccCertificateSecret;
published
/// the first characters of the .private file holding the secret key
// - equals '' by default, meaning no private secret is defined
// - you may use the FileName property instead to specify a full path name
property Serial: RawUtf8
read fSerial write fSerial;
/// the first characters of the .private file holding the secret key
// - equals '' by default, meaning no private secret is defined
// - you may use the Serial property instead to search in an application
// specific folder
property FileName: TFileName
read fFileName write fFileName;
/// the password used to protect the .private file
// - matches the -authpass parameter used with "ECC decrypt" command, but
// with TObjectWithPassword encryption
// - i.e. matches ConstName_CYPH as generated by TEccCertificateSecret.SaveToSource
property Password: SpiUtf8
read fPassword write fPassword;
/// number of PBKDF2 rounds to be applied to the associated password
// - matches ConstName_ROUNDS as generated by TEccCertificateSecret.SaveToSource
// - matches the -authrounds parameter used with "ECC decrypt" command
// - default is DEFAULT_ECCROUNDS, i.e. 60000
property PasswordRounds: integer
read fPasswordRounds write fPasswordRounds;
end;
/// store settings pointing to a local .private file containing a secret key
// for .synecc file decryption
// - following TEccCertificateSecret secure binary file format
// - publishes Salt and SaltRounds values, as expected by
// TEccCertificateSecret.Decrypt method
TEccCertificateDecryptSetting = class(TEccCertificateSecretSetting)
protected
fSalt: RawUtf8;
fSaltRounds: integer;
public
/// initialize the settings with default values
constructor Create; override;
published
/// the Salt passphrase used to protect the .synecc encrypted file
// - matches the -saltpass parameter used with "ECC crypt" command
// - default is 'salt'
property Salt: RawUtf8
read fSalt write fSalt;
/// number of PBKDF2 rounds to be applied to the associated Salt
// - matches the -saltrounds parameter used with "ECC crypt" command
// - default is DEFAULT_ECCROUNDS, i.e. 60000
property SaltRounds: integer
read fSaltRounds write fSaltRounds;
end;
/// a ECDSA secp256r1 digital signature of some content, signed by an authority
TEccSignatureCertified = class(TSynPersistent)
protected
fCertified: TEccSignatureCertifiedContent;
function GetAuthorityIssuer: RawUtf8;
function GetAuthoritySerial: RawUtf8;
function GetDate: RawUtf8;
public
/// initialize this signature
constructor Create; override;
/// compute a new signature of some digital content
// - memory buffer will be hashed using SHA-256, then will be signed using
// ECDSA over the private secret key of the supplied Authority certificate
constructor CreateNew(Authority: TEccCertificateSecret;
Data: pointer; Len: integer); overload;
/// compute a new signature of some digital content hash
// - supplied hash is likely to be from SHA-256, but could be e.g. crc256c
// - the hash will be signed using ECDSA over the private secret key of
// the supplied Authority certificate
constructor CreateNew(Authority: TEccCertificateSecret; const Hash: THash256); overload;
/// initialize this signature from a supplied binary
// - will raise an EEccException if the supplied binary content is incorrect
constructor CreateFrom(const binary: TEccSignatureCertifiedContent;
NoException: boolean = false);
/// initialize this signature from a supplied Base64 encoded binary
// - will raise an EEccException if the supplied base64 is incorrect
constructor CreateFromBase64(const base64: RawUtf8;
NoException: boolean = false);
/// initialize this signature from the "sign": field of a JSON .sign file
// - will raise an EEccException if the supplied file is incorrect
constructor CreateFromFile(const signfilename: TFileName;
NoException: boolean = false);
/// fast check of the binary buffer storage of this signature
// - performs basic checks, avoiding any void date, authority or signature
// - use Verify() or TEccCertificateChain.IsSigned() methods for full
// digital signature validation
function Check: boolean;
/// check if this digital signature matches a given data hash
// - will check internal properties of the certificate (e.g. validity dates),
// and validate the stored ECDSA signature according to the public key of
// the supplied signing authority
// - supplied hash is likely to be from SHA-256, but could be e.g. crc256c
// - this method is thread-safe, and not blocking
function Verify(Authority: TEccCertificate; const hash: THash256;
TimeUtc: TDateTime = 0): TEccValidity; overload;
/// check if this digital signature matches a given memory buffer
// - will check internal properties of the certificate (e.g. validity dates),
// and validate the stored ECDSA signature according to the public key of
// the supplied signing authority
// - will compute and verify the SHA-256 hash of the supplied data
// - this method is thread-safe, and not blocking
function Verify(Authority: TEccCertificate; Data: pointer; Len: integer;
TimeUtc: TDateTime = 0): TEccValidity; overload;
/// persist the signature as some Base64 encoded binary
function ToBase64: RawUtf8;
/// persist the signature as raw TEccSignatureCertifiedContent binary buffer
function ToBinary: RawByteString;
/// returns a TDocVariant object of all published properties of this instance
function ToVariant: variant; virtual;
/// retrieve the signature from some Base64 encoded binary
// - returns true on success, false otherwise
function FromBase64(const base64: RawUtf8): boolean;
/// retrieve the signature from the "sign": field of a JSON .sign file
// - returns true on success, false otherwise
function FromFile(const signfilename: TFileName): boolean; virtual;
/// save the ECDSA signature into a ASN.1's binary DER buffer
// - note that DER content only stores the ECDSA digital signature, so
// all certification information is lost
function SaveToDerBinary: RawByteString;
/// save the ECDSA signature into a ASN.1's binary DER file
// - note that DER content only stores the ECDSA digital signature, so
// all certification information is lost - consider using
// TEccSignatureCertifiedFile instead
// - returns TRUE on success, FALSE otherwise
function SaveToDERFile(const FileName: TFileName): boolean;
/// save the ECDSA signature into a X509 PEM text
// - PEM is just a base64-encoded DER with some minimal header/footer
// - note that PEM/DER content only stores the ECDSA digital signature, so
// all certification information is lost
function SaveToPemText: RawUtf8;
/// save the ECDSA signature into a X509 PEM file
// - note that PEM/DER content only stores the ECDSA digital signature, so
// all certification information is lost - consider using
// TEccSignatureCertifiedFile instead
// - returns TRUE on success, FALSE otherwise
function SaveToPEMFile(const FileName: TFileName): boolean;
/// low-level access to the binary buffer used ECDSA secp256r1 cryptography
// - you should not use this property, but other methods
property Certified: TEccSignatureCertifiedContent
read fCertified write fCertified;
published
/// the TEccSignatureCertified format version
// - currently equals 1
property Version: word
read fCertified.Version;
/// when this signature was generated, as ISO-8601 text
property Date: RawUtf8
read GetDate;
/// hexadecimal text of the authority certificate identifier used for signing
property AuthoritySerial: RawUtf8
read GetAuthoritySerial;
/// identify the authoritify issuer used for signing, as text
property AuthorityIssuer: RawUtf8
read GetAuthorityIssuer;
end;
/// handle a .sign file content as generated by TEccCertificateSecret.SignFile
// - JSON document of a SHA-256/ECDSA secp256r1 digital signature
TEccSignatureCertifiedFile = class(TEccSignatureCertified)
protected
fLowLevelInfo: TDocVariantData;
fMd5Digest: TMd5Digest;
fSha256Digest: TSha256Digest;
fMetaData: variant;
fSize: integer;
fMD5: RawUtf8;
fSHA256: RawUtf8;
public
/// create and set .sign fields after TEccCertificateSecret.Decrypt() process
// - will compute Size, and MD5/SHA-256 hashes from aDecryptedContent
// - will raise an EEccException if the supplied parameters are incorrect
constructor CreateFromDecryptedFile(const aDecryptedContent: RawByteString;
const Signature: TEccSignatureCertifiedContent; const MetaData: RawJson);
/// read a .sign digital signature file
// - as previously generated by TEccCertificateSecret.SignFile
// - will append '.sign' to aFileName, if it does not match this extension
// - returns true on success, false otherwise
function FromFile(const aFileName: TFileName): boolean; override;
/// read a .sign digital signature JSON content
// - as previously generated by TEccCertificateSecret.SignFile
// - returns true on success, false otherwise
function FromFileJson(const aFileContent: RawUtf8): boolean;
/// compute .sign fields after TEccCertificateSecret.Decrypt() process
// - will compute Size, and MD5/SHA-256 hashes from aDecryptedContent
function FromDecryptedFile(const aDecryptedContent: RawByteString;
const Signature: TEccSignatureCertifiedContent; const MetaData: RawJson): boolean;
/// low-level access to the whole JSON document members
property LowLevelInfo: TDocVariantData
read fLowLevelInfo;
/// the MD5 binary hash as stored in the .sign file
property Md5Digest: TMd5Digest
read fMd5Digest;
/// the SHA-256 binary hash as stored in the .sign file
property Sha256Digest: TSha256Digest
read fSha256Digest;
published
/// the meta data document as stored in the .sign file
property MetaData: variant
read fMetaData;
/// the signed file size in bytes, as stored in the .sign file
property Size: integer
read fSize;
/// the MD5 hexadecimal signature as stored in the .sign file
property MD5: RawUtf8
read fMD5;
/// the SHA-256 hexadecimal signature as stored in the .sign file
property SHA256: RawUtf8
read fSHA256;
end;
/// manage PKI certificates using ECC secp256r1 cryptography
// - will implement a simple and efficient public-key infrastructure (PKI),
// based on JSON objects or even plain Base64 encoded JSON strings
// - store certificates list and revoked serials (CRL)
TEccCertificateChain = class(TObjectRWLightLock)
protected
fItems: TEccCertificateObjArray;
fCrl: TEccCertificateRevocationDynArray;
fMaxVersion: byte;
fIsValidCached: boolean;
fIsValidCacheCount: integer;
fIsValidCache: THash128DynArray; // low TEccCertificateContent.ComputeHash
function GetCount: integer;
{$ifdef HASINLINE} inline; {$endif}
function GetCrlCount: integer;
{$ifdef HASINLINE} inline; {$endif}
procedure LockedClear;
function InternalAdd(cert: TEccCertificate; expected: TEccValidity): PtrInt;
procedure SetIsValidCached(const Value: boolean);
public
/// initialize a blank certificate store
constructor Create; override;
/// initialize a blank store with an explicit maximum version support
constructor CreateVersion(MaxVers: integer);
/// initialize the certificate store from some JSON array of strings
// - the serialization format is just a JSON array of Base64 encoded
// certificates (with only public keys) - so diverse from CreateFromFile()
// - will call LoadFromJson(), and raise EEccException on any error
constructor CreateFromJson(const json: RawUtf8; maxvers: integer = 2);
/// initialize the certificate store from an array of Base64 encoded strings
// - a TRawUtf8DynArray value is very convenient when storing the
// certificates chain as part of JSON settings, e.g. TDDDAppSettings
// - will call LoadFromArray(), and raise EEccException on any error
constructor CreateFromArray(const values: TRawUtf8DynArray;
maxvers: integer = 2);
/// finalize the certificate store
destructor Destroy; override;
/// delete all stored certificates
// - this method is thread-safe, calling Safe.WriteLock/WriteUnlock
procedure Clear;
/// search for a certificate from its hexadecimal text identifier
// - this method is not thread-safe, unless you use Safe.ReadLock/ReadUnlock
function GetBySerial(const Serial: RawUtf8): TEccCertificate; overload;
/// search for a certificate from its binary identifier
// - this method is not thread-safe, unless you use Safe.ReadLock/ReadUnlock
function GetBySerial(const Serial: TEccCertificateID): TEccCertificate; overload;
/// search for a certificate public key from its binary identifier
// - returns ecvValidSigned/ecvValidSelfSigned if the Serial identifier
// was found and not deprecated/revoked, for the proper Usage
// - returns ecvUnknownAuthority/ecvDeprecatedAuthority/ecvRevoked/ecvWrongUsage
// otherwise
// - this method is thread-safe, since it makes a private copy of the key
function GetKeyBySerial(const Serial: TEccCertificateID; Usage: TCryptCertUsages;
out PublicKey: TEccPublicKey; Valid: TEccValidity = ecvUnknown;
TimeUtc: TDateTime = 0; IgnoreDate: boolean = false): TEccValidity;
/// quickly check if a given certificate ID is part of the CRL
// - will check the internal Certificate Revocation List and the current date
// - returns crrNotRevoked is the serial is not known as part of the CRL
// - returns the reason why this certificate has been revoked otherwise
function IsRevoked(const Serial: RawUtf8): TCryptCertRevocationReason; overload;
/// quickly check if a given certificate ID is part of the CRL
// - will check the internal Certificate Revocation List and the current date
// - returns crrNotRevoked is the serial is not known as part of the CRL
// - returns the reason why this certificate has been revoked otherwise
function IsRevoked(const Serial: TEccCertificateID): TCryptCertRevocationReason; overload;
/// add a new Serial number to the internal Certificate Revocation List
// - you can set Reason as crrNotRevoked to remove a previous revocation
function Revoke(const Serial: RawUtf8; RevocationDate: TDateTime;
Reason: TCryptCertRevocationReason): boolean; overload;
/// add a new Serial number to the internal Certificate Revocation List
// - you can set Reason as crrNotRevoked to remove a previous revocation
function Revoke(const Serial: TEccCertificateID; RevocationDate: TDateTime;
Reason: TCryptCertRevocationReason): boolean; overload;
/// check if the certificate is valid, against known certificates chain
// - will check internal properties of the certificate (e.g. validity dates),
// and validate the stored ECDSA signature according to the public key of
// the associated signing authority (which should be stored in Items[])
// - consider setting IsValidCached property to TRUE to reduce resource use
// - this method is thread-safe, and not blocking
function IsValid(cert: TEccCertificate;
TimeUtc: TDateTime = 0): TEccValidity; overload;
/// check if the raw certificate is valid, against known certificates chain
// - will check internal properties of the certificate (e.g. validity dates,
// unless ignoreDate=TRUE), and validate the stored ECDSA signature
// according to the public key of the associated signing authority (which
// should be valid, and stored in Items[])
// - self-signed certificates should be registered with AddSelfSigned() or
// allowPlainSelfSigned will allow them even without AddSelfSigned()
// - consider setting IsValidCached property to TRUE to reduce resource use
// - this method is thread-safe, and not blocking
function IsValidRaw(const content: TEccCertificateContent;
ignoreDate: boolean = false; allowPlainSelfSigned: boolean = false;
TimeUtc: TDateTime = 0): TEccValidity;
/// check all stored certificates and their authorization chain
// - returns nil if all items were valid
// - returns the list of any invalid instances
// - do not free the returned items, since they are reference to Items[]
// - this method is not thread-safe so should be run e.g. just after loading
function ValidateItems: TEccCertificateObjArray;
/// check if the digital signature is recognized by the stored certificates
// - ensure that sign.AuthoritySerial is part of Items[] list but not the CRL
// - this method won't perform the ECDSA verification: use IsSigned() instead
// - this method is thread-safe, and not blocking
function IsAuthorized(sign: TEccSignatureCertified): boolean; overload;
/// check if the digital signature is recognized by the stored certificates
// - ensure that sign.AuthoritySerial is part of Items[] list but not the CRL
// - this method won't perform the ECDSA verification: use IsSigned() instead
// - this method is thread-safe, and not blocking
function IsAuthorized(const sign: TEccSignatureCertifiedContent): boolean; overload;
/// check if the digital signature is recognized by the stored certificates
// - will check that the supplied base64 encoded text is a ECC signature,
// and that its AuthoritySerial is part of the Items[] list
// - this method won't perform the ECDSA verification: use IsSigned() instead
// - this method is thread-safe, and not blocking
function IsAuthorized(const base64sign: RawUtf8): boolean; overload;
/// check if the digital signature of a given data hash is valid
// - will check internal properties of the certificate (e.g. validity dates),
// and validate the stored ECDSA signature according to the public key of
// the associated signing authority (which should be stored in Items[])
// - supplied hash is likely to be from SHA-256, but could be e.g. crc256c
// - this method is thread-safe, and not blocking
function IsSigned(sign: TEccSignatureCertified; const hash: THash256): TEccValidity; overload;
/// check if the digital signature of a given memory buffer is valid
// - if sign is a TEccSignatureCertifiedFile, the Size, MD5 and SHA256 fields
// stored in the .sign file content will be checked against the supplied data
// before ECDSA signature, and would return ecvCorrupted on error
// - it will then check internal properties of the certificate (e.g. validity
// dates), and validate the stored SHA-256/ECDSA signature according to the
// public key of the associated signing authority (stored in Items[])
// - this method is thread-safe, and not blocking
function IsSigned(sign: TEccSignatureCertified;
Data: pointer; Len: integer): TEccValidity; overload;
/// check if the digital signature file (.sign content) is valid
// - will check internal properties of the certificate (e.g. validity dates),
// and validate the stored ECDSA signature according to the public key of
// the associated signing authority (which should be stored in Items[])
// - will use TEccSignatureCertifiedFile Size, MD5 and SHA256 fields,
// so could be used without any actual memory buffer
// - this method is thread-safe, and not blocking
function IsSigned(sign: TEccSignatureCertifiedFile): TEccValidity; overload;
/// check if the digital signature of a given data hash is valid
// - will check internal properties of the certificate (e.g. validity dates),
// and validate the stored ECDSA signature according to the public key of
// the associated signing authority (which should be stored in Items[])
// - supplied hash is likely to be from SHA-256, but could be e.g. crc256c