-
Notifications
You must be signed in to change notification settings - Fork 4
/
MultiRecipientHybridEncryptionSignFrm.pas
935 lines (878 loc) · 30.8 KB
/
MultiRecipientHybridEncryptionSignFrm.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
{******************************************************************************}
{ }
{ WinRT Crypto Sample Applications }
{ Copyright (c) 2023 Christoph Schneider }
{ Schneider Infosystems AG, Switzerland }
{ https://github.com/SchneiderInfosystems/WinRTCrypto }
{ }
{******************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{******************************************************************************}
unit MultiRecipientHybridEncryptionSignFrm;
interface
uses
Winapi.Windows, Winapi.Messages,
System.Types, System.SysUtils, System.StrUtils, System.Classes, System.Win.WinRT,
System.Win.ComObj,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
Vcl.ComCtrls,
Winapi.CommonTypes, Winapi.WinRT,
Winapi.Security.Cryptography;
type
TFrmMultiRecipientHybridEncryptionSign = class(TForm)
ShapeResult: TShape;
LabelAlgo: TLabel;
LabelKey: TLabel;
LabelResult: TLabel;
LabelSymKeySize: TLabel;
cboSymAlgo: TComboBox;
EditSessionKey: TEdit;
btnEncrypt: TButton;
edtEncryptedPayload: TEdit;
btnDecrypt: TButton;
cboSymKeySize: TComboBox;
MemoClear: TMemo;
MemoResult: TMemo;
Label1: TLabel;
cboAsymAlgo: TComboBox;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
EditDecryptedSessionKey: TEdit;
LabelDecryptedSessionKeySize: TLabel;
btnSaveEncryptedMsg: TButton;
SaveDialog: TSaveDialog;
btnLoadEncryptedMessage: TButton;
OpenDialog: TOpenDialog;
OpenDialogPrivateKey: TOpenDialog;
OpenDialogPublicKey: TOpenDialog;
Label2: TLabel;
Label6: TLabel;
PageControl: TPageControl;
tabKeys: TTabSheet;
tabEncryption: TTabSheet;
TabDecryption: TTabSheet;
btnCreatePersonalKeys: TButton;
btnSavePersonalKeys: TButton;
btnLoadKeys: TButton;
btnLoadPubKey: TButton;
LabelPublicKey: TLabel;
edtPublicKey: TEdit;
LabelPrivateKey: TLabel;
edtPrivateKey: TEdit;
edtKeyName: TEdit;
Label7: TLabel;
lstRecipients: TListBox;
Label8: TLabel;
btnAddRecipient: TButton;
btnClearRecipients: TButton;
lstHeader: TListBox;
Label9: TLabel;
edtPersonalPrivateKey: TEdit;
Label10: TLabel;
edtPersonalName: TEdit;
btnLoadPersonalKey: TButton;
edtPersonalPublicKey: TEdit;
Label11: TLabel;
lblHeaderSize: TLabel;
lblPayloadSize: TLabel;
lblKeysSize: TLabel;
cboAsymKeySize: TComboBox;
lblHintPublicKeyMissingInHeader: TLabel;
btnAddCreatedKeyAsRecipient: TButton;
gpbEncryptedMessage: TGroupBox;
btnLoadCreatedKeys: TButton;
LabelIV: TLabel;
edtIV: TEdit;
Label12: TLabel;
edtSignature: TEdit;
Label13: TLabel;
edtSenderPrivateKey: TEdit;
btnAddCreatedKeyAsSender: TButton;
Label14: TLabel;
edtSenderPublicKey: TEdit;
btnLoadSenderPublicKey: TButton;
edtSenderName: TEdit;
procedure btnEncryptClick(Sender: TObject);
procedure btnDecryptClick(Sender: TObject);
procedure btnCreatePersonalKeysClick(Sender: TObject);
procedure cboAlgosChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnSavePersonalKeysClick(Sender: TObject);
procedure btnLoadKeysClick(Sender: TObject);
procedure btnLoadPubKeyClick(Sender: TObject);
procedure btnSaveEncryptedMsgClick(Sender: TObject);
procedure btnLoadEncryptedMessageClick(Sender: TObject);
procedure btnAddRecipientClick(Sender: TObject);
procedure btnClearRecipientsClick(Sender: TObject);
procedure btnLoadPersonalKeyClick(Sender: TObject);
procedure CheckKeySizes(Sender: TObject);
procedure btnAddCreatedKeyAsRecipientClick(Sender: TObject);
procedure btnLoadCreatedKeysClick(Sender: TObject);
procedure btnAddCreatedKeyAsSenderClick(Sender: TObject);
procedure btnLoadSenderPublicKeyClick(Sender: TObject);
private
function SelectedAsymAlgo: Core_IAsymmetricKeyAlgorithmProvider;
function SelectedAsymSignAlgo: Core_IAsymmetricKeyAlgorithmProvider;
function SelectAsymKeySizeInBits: integer;
function SelectedSymAlgo: Core_ISymmetricKeyAlgorithmProvider;
function SelectSymKeySizeInBytes: integer;
function SelectSymAlgoRequiresIV: boolean;
function SelectSymAlgoRequiresPadding: boolean;
function DataFolder: string;
procedure CheckActions;
procedure ShowError(const Msg: string);
procedure ShowWarning(const Msg: string);
procedure ShowResult(const Msg: string);
procedure ClearResult;
procedure CalcMessageSize;
function SearchEncryptedSessionKeyByPublicKeyInHeaders(const PublicKey: string): string;
function ImportPublicKey(const PublicKeyAsBase64: string): Core_ICryptographicKey;
function ImportPrivateKey(const PrivateKeyAsBase64: string): Core_ICryptographicKey;
function ImportPrivateKeyForSign(const PrivateKeyAsBase64: string): Core_ICryptographicKey;
function ImportPublicKeyForVerify(const PublicKeyAsBase64: string): Core_ICryptographicKey;
function AsymmetricEncrypt(PublicKey: Core_ICryptographicKey; SessionKey: IBuffer): IBuffer;
function AsymmetricDecrypt(PrivatKey: Core_ICryptographicKey; EntireMessage: IBuffer): IBuffer;
function AsymmetricSign(PrivateKey: Core_ICryptographicKey; EntireMessage: IBuffer): IBuffer;
function AsymmetricVerify(PublicKey: Core_ICryptographicKey; Encrypted, Signature: IBuffer): boolean;
function SymmetricEncrypt(SessionKey, ClearText, IV: IBuffer): IBuffer;
function SymmetricDecrypt(SessionKey, Encrypted, IV: IBuffer): IBuffer;
function EntireMessageForSign: IBuffer;
end;
var
FrmMultiRecipientHybridEncryptionSign: TFrmMultiRecipientHybridEncryptionSign;
implementation
uses
Winapi.Security.Helpers;
{$R *.dfm}
resourcestring
{$IFDEF VER360}
rsTS = '''
This is a sample text for hybrid encryption based on symmetric algo %s and asymmetric algo %s.
The creation date and time of this test text is %s %s. Its built with Delphi 12!
It contains also unicode letters Ж•₱₲₳‡₾ to test UTF8 encoding.
''';
{$ELSE}
rsTS =
'This is a sample text for hybrid encryption based on symmetric algo %s and asymmetric algo %s.'#13#10 +
'The creation date and time of this test text is %s %s.'#13#10 +
'It contains also unicode letters Ж•₱₲₳‡₾ to test UTF8 encoding.';
{$ENDIF}
rsKeySize = 'Key size %d [bits]';
rsPublicAndPrivateKeySize = 'Public key size %d / Private key size %d [bytes]';
rsHeaderSize = '%d Recipient(s) in header, size %d [~bytes]';
rsPayloadSize = 'Payload size %d [bytes]';
{ TFrmHybridEncryption }
{$REGION 'GUI Handling'}
procedure TFrmMultiRecipientHybridEncryptionSign.FormCreate(Sender: TObject);
begin
lstHeader.Clear;
edtEncryptedPayload.Text := '';
ClearResult;
cboAlgosChange(nil);
CheckActions;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.cboAlgosChange(Sender: TObject);
begin
MemoClear.Text :=
Format(rsTS, [cboSymAlgo.Text, cboAsymAlgo.Text, DateToStr(now), TimeToStr(Now)]);
end;
procedure TFrmMultiRecipientHybridEncryptionSign.CheckKeySizes(Sender: TObject);
begin
ClearResult;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.CheckActions;
var
IsClearTextDefined: boolean;
IsPublicKeyDefined: boolean;
IsPrivateKeyDefined: boolean;
IsNameDefined: boolean;
IsPersonalPublicKeyDefined: boolean;
IsPersonalPrivateKeyDefined: boolean;
IsPublicKeyInHeader: boolean;
IsPayloaded: boolean;
AreRecipientsDefined: boolean;
AreHeaderItemsPresent: boolean;
begin
IsClearTextDefined := length(MemoClear.Text) > 0;
IsPublicKeyDefined := length(edtPublicKey.Text) > 0;
IsPrivateKeyDefined := length(edtPrivateKey.Text) > 0;
IsPersonalPublicKeyDefined := length(edtPersonalPublicKey.Text) > 0;
IsPersonalPrivateKeyDefined := length(edtPersonalPrivateKey.Text) > 0;
IsPublicKeyInHeader := not SearchEncryptedSessionKeyByPublicKeyInHeaders(
edtPersonalPublicKey.Text).IsEmpty;
IsNameDefined := length(edtKeyName.Text) > 0;
IsPayloaded := length(edtEncryptedPayload.Text) > 0;
AreRecipientsDefined := lstRecipients.Count > 0;
AreHeaderItemsPresent := lstHeader.Count > 0;
// Enable/disable button states
btnAddCreatedKeyAsRecipient.Enabled := IsPublicKeyDefined and IsNameDefined;
btnAddCreatedKeyAsRecipient.Enabled := IsPublicKeyDefined and IsNameDefined;
btnLoadCreatedKeys.Enabled :=
IsPublicKeyDefined and IsNameDefined and IsPrivateKeyDefined;
btnSavePersonalKeys.Enabled := IsPublicKeyDefined;
btnEncrypt.Enabled := AreRecipientsDefined and IsClearTextDefined;
btnDecrypt.Enabled :=
IsPersonalPrivateKeyDefined and IsPublicKeyInHeader and IsPayloaded;
lblHintPublicKeyMissingInHeader.Visible := IsPersonalPublicKeyDefined and
AreHeaderItemsPresent and not IsPublicKeyInHeader;
end;
{$ENDREGION}
{$REGION 'Result Panel'}
procedure TFrmMultiRecipientHybridEncryptionSign.ShowError(const Msg: string);
begin
ShapeResult.Brush.Color := clRed;
LabelResult.Caption := Msg;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.ShowWarning(const Msg: string);
begin
ShapeResult.Brush.Color := clYellow;
LabelResult.Caption := Msg;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.ShowResult(const Msg: string);
begin
ShapeResult.Brush.Color := clLime;
LabelResult.Caption := Msg;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.ClearResult;
begin
ShapeResult.Brush.Color := clBtnFace;
LabelResult.Caption := '';
end;
{$ENDREGION}
{$REGION 'Key Management'}
procedure TFrmMultiRecipientHybridEncryptionSign.btnCreatePersonalKeysClick(Sender: TObject);
var
PersonalKey: Core_ICryptographicKey;
PublicKey, PrivateKey: IBuffer;
begin
Screen.Cursor := crHourGlass;
try
PersonalKey := SelectedAsymAlgo.CreateKeyPair(SelectAsymKeySizeInBits);
finally
Screen.Cursor := crDefault;
end;
if assigned(PersonalKey) then
begin
PublicKey := PersonalKey.ExportPublicKey;
PrivateKey := PersonalKey.Export(
Core_CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo);
edtPublicKey.Text := TWinRTCryptoHelpers.EncodeAsBase64(PublicKey);
edtPrivateKey.Text := TWinRTCryptoHelpers.EncodeAsBase64(PrivateKey);
lblKeysSize.Caption := Format(rsPublicAndPrivateKeySize,
[PublicKey.Length, PrivateKey.Length]);
if edtKeyName.Text = '' then
edtKeyName.Text := 'Myself'
else if edtKeyName.Text = 'Myself' then
edtKeyName.Text := 'Alice'
else if edtKeyName.Text = 'Alice' then
edtKeyName.Text := 'Bob';
// Transfer automatically to decrypt tab
btnLoadCreatedKeysClick(nil);
end;
CheckActions;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.btnSavePersonalKeysClick(Sender: TObject);
var
sl: TStringList;
begin
if length(edtKeyName.Text) = 0 then
edtKeyName.SetFocus
else begin
sl := TStringList.Create;
try
sl.Text := edtPublicKey.Text;
sl.SaveToFile(DataFolder + edtKeyName.Text + '.PublicKey');
sl.Text := edtPrivateKey.Text ;
sl.SaveToFile(DataFolder + edtKeyName.Text + '.PrivateKey');
finally
sl.Free;
end;
end;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.btnLoadKeysClick(Sender: TObject);
var
sl: TStringList;
PersonalKey: Core_ICryptographicKey;
PublicKey, PrivateKey: IBuffer;
begin
OpenDialogPrivateKey.InitialDir := DataFolder;
if OpenDialogPrivateKey.Execute(Handle) then
begin
sl := TStringList.Create;
try
sl.LoadFromFile(OpenDialogPrivateKey.FileName);
edtPrivateKey.Text := trim(sl.Text);
PrivateKey := TWinRTCryptoHelpers.DecodeFromBase64(edtPrivateKey.Text);
finally
sl.Free;
end;
PersonalKey := ImportPrivateKey(edtPrivateKey.Text);
if assigned(PersonalKey) then
begin
PublicKey := PersonalKey.ExportPublicKey;
cboAsymKeySize.ItemIndex :=
cboAsymKeySize.Items.IndexOf(PersonalKey.KeySize.ToString);
cboAsymKeySize.Enabled := false;
lblKeysSize.Caption := Format(rsPublicAndPrivateKeySize,
[PublicKey.Length, PrivateKey.Length]);
edtPublicKey.Text := TWinRTCryptoHelpers.EncodeAsBase64(PublicKey);
edtKeyName.Text :=
ChangeFileExt(ExtractFileName(OpenDialogPrivateKey.FileName), '');
end;
CheckActions;
end;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.btnLoadPubKeyClick(Sender: TObject);
var
sl: TStringList;
begin
OpenDialogPublicKey.InitialDir := DataFolder;
if OpenDialogPublicKey.Execute(Handle) then
begin
sl := TStringList.Create;
try
sl.LoadFromFile(OpenDialogPublicKey.FileName);
edtPublicKey.Text := trim(sl.Text);
edtPrivateKey.Text := '';
edtKeyName.Text :=
ChangeFileExt(ExtractFileName(OpenDialogPublicKey.FileName), '');
lblKeysSize.Caption := '';
finally
sl.Free;
end;
CheckActions;
end;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.btnLoadSenderPublicKeyClick(
Sender: TObject);
var
sl: TStringList;
begin
OpenDialogPublicKey.InitialDir := DataFolder;
if OpenDialogPublicKey.Execute(Handle) then
begin
sl := TStringList.Create;
try
sl.LoadFromFile(OpenDialogPublicKey.FileName);
edtSenderPublicKey.Text := trim(sl.Text);
edtSenderName.Text :=
ChangeFileExt(ExtractFileName(OpenDialogPublicKey.FileName), '');
finally
sl.Free;
end;
CheckActions;
end;
end;
{$ENDREGION}
{$REGION 'Message Encryption'}
procedure TFrmMultiRecipientHybridEncryptionSign.btnAddCreatedKeyAsRecipientClick(
Sender: TObject);
begin
lstRecipients.AddItem(edtKeyName.Text + ':' + edtPublicKey.Text, nil);
CheckActions;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.btnAddCreatedKeyAsSenderClick(
Sender: TObject);
begin
edtSenderPrivateKey.Text := edtPrivateKey.Text;
CheckActions;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.btnAddRecipientClick(
Sender: TObject);
var
sl: TStringList;
Name: string;
begin
OpenDialogPublicKey.InitialDir := DataFolder;
if OpenDialogPublicKey.Execute(Handle) then
begin
Name := ChangeFileExt(ExtractFileName(OpenDialogPublicKey.FileName), '');
sl := TStringList.Create;
try
sl.LoadFromFile(OpenDialogPublicKey.FileName);
lstRecipients.AddItem(Name + ':' + trim(sl.Text), nil);
finally
sl.Free;
end;
end;
CheckActions;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.btnClearRecipientsClick(
Sender: TObject);
begin
lstRecipients.Clear;
CheckActions;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.btnEncryptClick(Sender: TObject);
var
SessionKey: IBuffer;
Recipient: string;
RecipientNameAndKey: TStringDynArray;
PublicKeyAsStr: string;
PublicKey: Core_ICryptographicKey;
ClearData, IV: IBuffer;
EncryptedSessionKey: IBuffer;
Payload: IBuffer;
begin
lstHeader.Clear;
SessionKey := TCryptographicBuffer.GenerateRandom(SelectSymKeySizeInBytes);
EditSessionKey.Text := TWinRTCryptoHelpers.EncodeAsBase64(SessionKey);
LabelSymKeySize.Caption :=
Format(rsKeySize, [SelectedSymAlgo.CreateSymmetricKey(SessionKey).KeySize]);
for Recipient in lstRecipients.Items do
begin
RecipientNameAndKey := SplitString(Recipient, ':');
if length(RecipientNameAndKey) <> 2 then
raise Exception.Create('Invalid recipient format');
PublicKeyAsStr := RecipientNameAndKey[1];
PublicKey := ImportPublicKey(PublicKeyAsStr);
if assigned(PublicKey) then
begin
EncryptedSessionKey := AsymmetricEncrypt(PublicKey, SessionKey);
if not assigned(EncryptedSessionKey) then
exit;
lstHeader.AddItem(PublicKeyAsStr + ':' +
TWinRTCryptoHelpers.EncodeAsBase64(EncryptedSessionKey), nil);
end;
end;
if SelectSymAlgoRequiresIV then
IV := TCryptographicBuffer.GenerateRandom(SelectedSymAlgo.BlockLength)
else
IV := nil;
edtIV.Text := TWinRTCryptoHelpers.EncodeAsBase64(IV);
ClearData := TWinRTCryptoHelpers.StrToIBuffer(MemoClear.Text);
if SelectSymAlgoRequiresPadding then
begin
// Ensure that the message length is a multiple of the block length.
// This is not necessary for PKCS #7 algorithms which automatically pad the
// message to an appropriate length.
if ClearData.Length mod SelectedSymAlgo.BlockLength <> 0 then
begin
ShowWarning(
'Message length must be multiple of block length: Message padded now');
MemoClear.Text := MemoClear.Text + StringOfChar('_',
SelectedSymAlgo.BlockLength - ClearData.Length mod SelectedSymAlgo.BlockLength);
// A better solution would be to use a message length and a random pad
ClearData := TWinRTCryptoHelpers.StrToIBuffer(MemoClear.Text);
end;
end;
Payload := SymmetricEncrypt(SessionKey, ClearData, IV);
if assigned(Payload) then
begin
edtEncryptedPayload.Text := TWinRTCryptoHelpers.EncodeAsBase64(PayLoad);
edtSignature.Text := TWinRTCryptoHelpers.EncodeAsBase64(AsymmetricSign(
ImportPrivateKeyForSign(edtSenderPrivateKey.Text), EntireMessageForSign));
ClearResult;
end;
CalcMessageSize;
CheckActions;
end;
{$ENDREGION}
{$REGION 'Message Decryption'}
procedure TFrmMultiRecipientHybridEncryptionSign.btnLoadCreatedKeysClick(
Sender: TObject);
begin
// Load from key management tab
edtPersonalPublicKey.Text := edtPublicKey.Text;
edtPersonalPrivateKey.Text := edtPrivateKey.Text;
edtPersonalName.Text := edtKeyName.Text;
CheckActions;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.btnLoadPersonalKeyClick(Sender: TObject);
var
sl: TStringList;
PersonalKey: Core_ICryptographicKey;
begin
OpenDialogPrivateKey.InitialDir := DataFolder;
if OpenDialogPrivateKey.Execute(Handle) then
begin
sl := TStringList.Create;
try
sl.LoadFromFile(OpenDialogPrivateKey.FileName);
edtPersonalPrivateKey.Text := trim(sl.Text);
PersonalKey := ImportPrivateKey(edtPersonalPrivateKey.Text);
if assigned(PersonalKey) then
begin
edtPersonalPublicKey.Text :=
TWinRTCryptoHelpers.EncodeAsBase64(PersonalKey.ExportPublicKey);
edtPersonalName.Text :=
ChangeFileExt(ExtractFileName(OpenDialogPrivateKey.FileName), '');
end;
finally
sl.Free;
end;
CheckActions;
end;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.btnDecryptClick(Sender: TObject);
var
EncryptedSessionKey: string;
PrivateKey: Core_ICryptographicKey;
SessionKey: IBuffer;
ClearText: IBuffer;
begin
ClearResult;
EncryptedSessionKey :=
SearchEncryptedSessionKeyByPublicKeyInHeaders(edtPersonalPublicKey.Text);
if EncryptedSessionKey.IsEmpty then
ShowError('This message is not encrypted for given public key')
else begin
PrivateKey := ImportPrivateKey(edtPersonalPrivateKey.Text);
if assigned(PrivateKey) then
begin
SessionKey := AsymmetricDecrypt(PrivateKey,
TWinRTCryptoHelpers.DecodeFromBase64(EncryptedSessionKey));
if assigned(SessionKey) then
begin
EditDecryptedSessionKey.Text :=
TWinRTCryptoHelpers.EncodeAsBase64(SessionKey);
LabelDecryptedSessionKeySize.Caption := Format(rsKeySize,
[SelectedSymAlgo.CreateSymmetricKey(SessionKey).KeySize]);
ClearText := SymmetricDecrypt(SessionKey,
TWinRTCryptoHelpers.DecodeFromBase64(edtEncryptedPayload.Text),
TWinRTCryptoHelpers.DecodeFromBase64(edtIV.Text));
if assigned(ClearText) then
begin
MemoResult.Text := TWinRTCryptoHelpers.IBufferToStr(ClearText);
if AsymmetricVerify(ImportPublicKeyForVerify(edtSenderPublicKey.Text),
EntireMessageForSign,
TWinRTCryptoHelpers.DecodeFromBase64(edtSignature.Text)) then
begin
edtSignature.Color := clLime;
if SameText(MemoClear.Text, MemoResult.Text) then
ShowResult(
'Passed: Resulting clear text is identical to starting clear text')
else
ShowWarning(
'Failed: Resulting clear text different than starting clear text');
end else begin
edtSignature.Color := clred;
ShowWarning('Sender verification failed')
end;
end;
end;
end;
end;
end;
function TFrmMultiRecipientHybridEncryptionSign.SearchEncryptedSessionKeyByPublicKeyInHeaders(
const PublicKey: string): string;
var
c: integer;
header: string;
publicKeyAndEncyptedSessionKey: TStringDynArray;
begin
result := '';
for c := 0 to pred(lstHeader.Items.Count) do
begin
header := lstHeader.Items[c];
publicKeyAndEncyptedSessionKey := SplitString(header, ':');
if length(publicKeyAndEncyptedSessionKey) <> 2 then
raise Exception.Create('Invalid header format');
if SameText(publicKeyAndEncyptedSessionKey[0], PublicKey) then
begin
lstHeader.ItemIndex := c;
exit(publicKeyAndEncyptedSessionKey[1]);
end;
end;
lstHeader.ItemIndex := -1;
end;
{$ENDREGION}
{$REGION 'Key Import'}
function TFrmMultiRecipientHybridEncryptionSign.ImportPrivateKey(
const PrivateKeyAsBase64: string): Core_ICryptographicKey;
begin
result := nil;
try
result := SelectedAsymAlgo.ImportKeyPair(
TWinRTCryptoHelpers.DecodeFromBase64(PrivateKeyAsBase64),
Core_CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo);
except
on e: exception do
ShowError('Import private key failed: ' + e.Message);
end;
end;
function TFrmMultiRecipientHybridEncryptionSign.ImportPublicKey(
const PublicKeyAsBase64: string): Core_ICryptographicKey;
begin
result := nil;
try
result := SelectedAsymAlgo.ImportPublicKey(
TWinRTCryptoHelpers.DecodeFromBase64(PublicKeyAsBase64));
except
on e: exception do
ShowError('Import public key failed: ' + e.Message);
end;
end;
function TFrmMultiRecipientHybridEncryptionSign.ImportPrivateKeyForSign(
const PrivateKeyAsBase64: string): Core_ICryptographicKey;
begin
result := nil;
try
result := SelectedAsymSignAlgo.ImportKeyPair(
TWinRTCryptoHelpers.DecodeFromBase64(PrivateKeyAsBase64),
Core_CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo);
except
on e: exception do
ShowError('Import private key for sign failed: ' + e.Message);
end;
end;
function TFrmMultiRecipientHybridEncryptionSign.ImportPublicKeyForVerify(
const PublicKeyAsBase64: string): Core_ICryptographicKey;
begin
result := nil;
try
result := SelectedAsymSignAlgo.ImportPublicKey(
TWinRTCryptoHelpers.DecodeFromBase64(PublicKeyAsBase64));
except
on e: exception do
ShowError('Import public key for verify failed: ' + e.Message);
end;
end;
{$ENDREGION}
{$REGION 'Asymmetric Encrypt/Decryption'}
function TFrmMultiRecipientHybridEncryptionSign.SelectedAsymAlgo:
Core_IAsymmetricKeyAlgorithmProvider;
var
Algo: HString;
begin
case cboAsymAlgo.ItemIndex of
0: Algo := TCore_AsymmetricAlgorithmNames.RsaPkcs1;
1: Algo := TCore_AsymmetricAlgorithmNames.RsaOaepSha1;
2: Algo := TCore_AsymmetricAlgorithmNames.RsaOaepSha256;
3: Algo := TCore_AsymmetricAlgorithmNames.RsaOaepSha384;
4: Algo := TCore_AsymmetricAlgorithmNames.RsaOaepSha512;
else
raise Exception.Create('Unknown Core_AsymmetricAlgorithmNames');
end;
result := TCore_AsymmetricKeyAlgorithmProvider.OpenAlgorithm(Algo);
cboAsymAlgo.Enabled := false;
end;
function TFrmMultiRecipientHybridEncryptionSign.SelectedAsymSignAlgo: Core_IAsymmetricKeyAlgorithmProvider;
var
Algo: HString;
begin
case cboAsymAlgo.ItemIndex of
0,
1: Algo := TCore_AsymmetricAlgorithmNames.RsaSignPkcs1Sha1;
2: Algo := TCore_AsymmetricAlgorithmNames.RsaSignPkcs1Sha256;
3: Algo := TCore_AsymmetricAlgorithmNames.RsaSignPkcs1Sha384;
4: Algo := TCore_AsymmetricAlgorithmNames.RsaSignPkcs1Sha512;
else
raise Exception.Create('Unknown Core_AsymmetricAlgorithmNames');
end;
result := TCore_AsymmetricKeyAlgorithmProvider.OpenAlgorithm(Algo);
cboAsymAlgo.Enabled := false;
end;
function TFrmMultiRecipientHybridEncryptionSign.SelectAsymKeySizeInBits: integer;
begin
result := StrToInt(cboAsymKeySize.Text);
cboAsymKeySize.Enabled := false;
end;
function TFrmMultiRecipientHybridEncryptionSign.AsymmetricEncrypt(
PublicKey: Core_ICryptographicKey; SessionKey: IBuffer): IBuffer;
begin
result := nil;
try
result := TCore_CryptographicEngine.Encrypt(PublicKey, SessionKey, nil);
except
on e: EOleException do
if e.ErrorCode = E_INVALIDARG then
ShowError('Asymmetric encryption failed by invalid argument: ' +
'Session key size must be smaller than recipient''s public key')
else
ShowError('Asymmetric encryption failed: ' + e.Message);
end;
end;
function TFrmMultiRecipientHybridEncryptionSign.AsymmetricDecrypt(
PrivatKey: Core_ICryptographicKey; EntireMessage: IBuffer): IBuffer;
begin
result := nil;
try
result := TCore_CryptographicEngine.Decrypt(PrivatKey, EntireMessage, nil);
except
on e: exception do
ShowError('Asymmetric decryption failed: ' + e.Message);
end;
end;
function TFrmMultiRecipientHybridEncryptionSign.AsymmetricSign(
PrivateKey: Core_ICryptographicKey; EntireMessage: IBuffer): IBuffer;
begin
result := nil;
try
result := TCore_CryptographicEngine.Sign(PrivateKey, EntireMessage);
except
on e: exception do
ShowError('Asymmetric sign failed: ' + e.Message);
end;
end;
function TFrmMultiRecipientHybridEncryptionSign.AsymmetricVerify(
PublicKey: Core_ICryptographicKey; Encrypted, Signature: IBuffer): boolean;
begin
result := false;
try
result := TCore_CryptographicEngine.VerifySignature(PublicKey, Encrypted, Signature);
except
on e: exception do
ShowError('Asymmetric verify failed: ' + e.Message);
end;
end;
{$ENDREGION}
{$REGION 'Symmetric Encrypt/Decryption'}
function TFrmMultiRecipientHybridEncryptionSign.SelectedSymAlgo:
Core_ISymmetricKeyAlgorithmProvider;
var
Algo: HString;
begin
case cboSymAlgo.ItemIndex of
0: Algo := TCore_SymmetricAlgorithmNames.AesCbc;
1: Algo := TCore_SymmetricAlgorithmNames.AesCbcPkcs7;
2: Algo := TCore_SymmetricAlgorithmNames.AesEcb;
3: Algo := TCore_SymmetricAlgorithmNames.AesEcbPkcs7;
else
raise Exception.Create('Unknown Core_SymmetricAlgorithmNames');
end;
result := TCore_SymmetricKeyAlgorithmProvider.OpenAlgorithm(Algo);
cboSymAlgo.Enabled := false;
end;
function TFrmMultiRecipientHybridEncryptionSign.SelectSymKeySizeInBytes: integer;
begin
result := StrToInt(cboSymKeySize.Text) div 8;
cboSymKeySize.Enabled := false;
end;
function TFrmMultiRecipientHybridEncryptionSign.SelectSymAlgoRequiresPadding: boolean;
begin
result := cboSymAlgo.ItemIndex in [0, 2]; // Without PKCS #7
end;
function TFrmMultiRecipientHybridEncryptionSign.SelectSymAlgoRequiresIV: boolean;
begin
result := cboSymAlgo.ItemIndex in [0, 1]; // Cbc block cipher mode
end;
function TFrmMultiRecipientHybridEncryptionSign.SymmetricEncrypt(SessionKey,
ClearText, IV: IBuffer): IBuffer;
var
key: Core_ICryptographicKey;
begin
result := nil;
key := SelectedSymAlgo.CreateSymmetricKey(SessionKey);
try
result := TCore_CryptographicEngine.Encrypt(key, ClearText, IV);
except
on e: exception do
ShowError('Symmetric encryption failed: ' + e.Message);
end;
end;
function TFrmMultiRecipientHybridEncryptionSign.SymmetricDecrypt(SessionKey,
Encrypted, IV: IBuffer): IBuffer;
var
key: Core_ICryptographicKey;
begin
result := nil;
key := SelectedSymAlgo.CreateSymmetricKey(SessionKey);
try
result := TCore_CryptographicEngine.Decrypt(key, Encrypted, IV);
except
on e: exception do
ShowError('Symmetric decryption failed: ' + e.Message);
end;
end;
{$ENDREGION}
{$REGION 'Encrypted Message Load/Save'}
function TFrmMultiRecipientHybridEncryptionSign.DataFolder: string;
begin
result := ExpandFileName(ExtractFileDir(Application.ExeName) + '\..\..\Data\');
if not DirectoryExists(result, false) then
ForceDirectories(result);
end;
function TFrmMultiRecipientHybridEncryptionSign.EntireMessageForSign: IBuffer;
var
sl: TStringList;
begin
sl := TStringList.Create;
try
sl.AddStrings(lstHeader.Items);
sl.Add(edtIV.Text);
sl.Add(edtEncryptedPayload.Text);
result := TWinRTCryptoHelpers.StrToIBuffer(sl.Text);
finally
sl.Free;
end;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.btnSaveEncryptedMsgClick(Sender: TObject);
var
sl: TStringList;
begin
SaveDialog.InitialDir := DataFolder;
SaveDialog.FileName := 'Message';
if SaveDialog.Execute(Handle) then
begin
sl := TStringList.Create;
try
sl.AddStrings(lstHeader.Items);
sl.Add(edtIV.Text);
sl.Add(edtEncryptedPayload.Text);
sl.Add(edtSignature.Text);
sl.SaveToFile(SaveDialog.FileName);
finally
sl.Free;
end;
end;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.btnLoadEncryptedMessageClick(Sender: TObject);
var
sl: TStringList;
begin
OpenDialog.InitialDir := DataFolder;
if OpenDialog.Execute(Handle) then
begin
sl := TStringList.Create;
try
sl.LoadFromFile(OpenDialog.FileName);
if sl.Count >= 4 then
begin
edtIV.Text := sl[sl.Count - 3];
edtEncryptedPayload.Text := sl[sl.Count - 2];
edtSignature.Text := sl[sl.Count - 1];
sl.Delete(sl.Count - 3);
sl.Delete(sl.Count - 2);
sl.Delete(sl.Count - 1);
lstHeader.Clear;
lstHeader.Items.AddStrings(sl);
CheckActions;
ClearResult;
CalcMessageSize;
end;
finally
sl.Free;
end;
end;
end;
procedure TFrmMultiRecipientHybridEncryptionSign.CalcMessageSize;
var
ClearData, IV: IBuffer;
Len: cardinal;
begin
lblHeaderSize.Caption :=
Format(rsHeaderSize,
[lstHeader.Items.Count, length(lstHeader.Items.Text) div 3]);
ClearData := TWinRTCryptoHelpers.DecodeFromBase64(edtEncryptedPayload.Text);
Len := ClearData.Length;
IV := TWinRTCryptoHelpers.DecodeFromBase64(edtIV.Text);
if assigned(IV) then
Len := Len + IV.Length;
lblPayloadSize.Caption := Format(rsPayloadSize, [Len]);
end;
{$ENDREGION}
end.