-
Notifications
You must be signed in to change notification settings - Fork 4
/
SymmetricEncryptionFrm.pas
364 lines (331 loc) · 11.3 KB
/
SymmetricEncryptionFrm.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
{******************************************************************************}
{ }
{ 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 SymmetricEncryptionFrm;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes, System.Win.WinRT,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
Winapi.CommonTypes, Winapi.WinRT,
Winapi.Security.Cryptography;
type
TFrmSymmetricEncryption = class(TForm)
LabelAlgo: TLabel;
cboAlgo: TComboBox;
btnCreateKey: TButton;
LabelKey: TLabel;
EditKey: TEdit;
EditClear: TEdit;
btnEncrypt: TButton;
EditEncrypted: TEdit;
btnDecrypt: TButton;
EditResult: TEdit;
LabelResult: TLabel;
ShapeResult: TShape;
btnSaveEncrypt: TButton;
btnLoadEncrypt: TButton;
btnSaveKey: TButton;
btnLoadKey: TButton;
LabelKeySize: TLabel;
EditKeySize: TEdit;
cboKeySize: TComboBox;
EditIV: TEdit;
LabelIV: TLabel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
procedure btnCreateKeyClick(Sender: TObject);
procedure btnEncryptClick(Sender: TObject);
procedure btnDecryptClick(Sender: TObject);
procedure btnSaveEncryptClick(Sender: TObject);
procedure cboAlgoChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnLoadEncryptClick(Sender: TObject);
procedure btnSaveKeyClick(Sender: TObject);
procedure btnLoadKeyClick(Sender: TObject);
procedure EditKeyChange(Sender: TObject);
procedure EditIVChange(Sender: TObject);
procedure EditEncryptedChange(Sender: TObject);
private
fDataFolder: string;
function SelectedAlgo: Core_ISymmetricKeyAlgorithmProvider;
function SelectKeySizeInBytes: integer;
function SelectAlgoRequiresIV: boolean;
function SelectAlgoRequiresPadding: boolean;
procedure CheckButtons;
procedure InitWithNewKeys;
procedure ShowError(const Msg: string);
procedure ShowWarning(const Msg: string);
procedure ShowResult(const Msg: string);
procedure ClearResult;
end;
var
FrmSymmetricEncryption: TFrmSymmetricEncryption;
implementation
uses
Winapi.Security.Helpers;
{$R *.dfm}
resourcestring
rsTS = 'Test sample for symmetrical encryption %s at %s with Unicode Ж•₱₲₳‡₾';
{$REGION 'GUI Handling'}
procedure TFrmSymmetricEncryption.FormCreate(Sender: TObject);
begin
cboAlgoChange(Sender);
end;
procedure TFrmSymmetricEncryption.cboAlgoChange(Sender: TObject);
begin
fDataFolder :=
IncludeTrailingPathDelimiter(
ExpandFileName(
ExtractFileDir(Application.ExeName) + '\..\..\Data\' + cboAlgo.Text));
if not DirectoryExists(fDataFolder, false) then
ForceDirectories(fDataFolder);
EditKey.Text := '';
btnEncrypt.Enabled := false;
btnDecrypt.Enabled := false;
btnSaveKey.Enabled := false;
EditClear.Text := Format(rsTS, [cboAlgo.Text, TimeToStr(Now)]);
btnLoadKey.Enabled := FileExists(fDataFolder + 'Private.key');
btnLoadEncrypt.Enabled := FileExists(fDataFolder + 'Encrypted.txt');
end;
procedure TFrmSymmetricEncryption.InitWithNewKeys;
begin
btnEncrypt.Enabled := true;
btnLoadEncrypt.Enabled := true;
btnDecrypt.Enabled := false;
btnSaveKey.Enabled := true;
EditEncrypted.Text := '';
EditResult.Text := '';
ClearResult;
end;
{$ENDREGION}
{$REGION 'Result Panel'}
procedure TFrmSymmetricEncryption.ShowError(const Msg: string);
begin
ShapeResult.Brush.Color := clRed;
LabelResult.Caption := Msg;
end;
procedure TFrmSymmetricEncryption.ShowWarning(const Msg: string);
begin
ShapeResult.Brush.Color := clYellow;
LabelResult.Caption := Msg;
end;
procedure TFrmSymmetricEncryption.ShowResult(const Msg: string);
begin
ShapeResult.Brush.Color := clLime;
LabelResult.Caption := Msg;
end;
procedure TFrmSymmetricEncryption.ClearResult;
begin
ShapeResult.Brush.Color := clBtnFace;
LabelResult.Caption := '';
end;
procedure TFrmSymmetricEncryption.EditEncryptedChange(Sender: TObject);
begin
CheckButtons;
end;
procedure TFrmSymmetricEncryption.EditIVChange(Sender: TObject);
begin
CheckButtons;
end;
procedure TFrmSymmetricEncryption.EditKeyChange(Sender: TObject);
begin
EditKey.Color := clWindow;
CheckButtons;
end;
procedure TFrmSymmetricEncryption.CheckButtons;
begin
btnDecrypt.Enabled := (length(EditEncrypted.Text) > 0) and
(length(EditIV.Text) > 0) and (length(EditEncrypted.Text) > 0);
end;
{$ENDREGION}
{$REGION 'Key Management'}
procedure TFrmSymmetricEncryption.btnCreateKeyClick(Sender: TObject);
var
KeyMat: IBuffer;
Key: Core_ICryptographicKey;
begin
KeyMat := TCryptographicBuffer.GenerateRandom(SelectKeySizeInBytes);
EditKey.Text := TWinRTCryptoHelpers.EncodeAsBase64(KeyMat);
Key := SelectedAlgo.CreateSymmetricKey(KeyMat);
EditKey.Color := clAqua;
EditKeySize.Text := Key.KeySize.ToString;
InitWithNewKeys;
end;
procedure TFrmSymmetricEncryption.btnSaveKeyClick(Sender: TObject);
var
sl: TStringList;
begin
sl := TStringList.Create;
try
sl.Text := EditKey.Text;
sl.SaveToFile(fDataFolder + 'Private.key');
finally
sl.Free;
end;
end;
procedure TFrmSymmetricEncryption.btnLoadKeyClick(Sender: TObject);
var
sl: TStringList;
KeyMat: IBuffer;
Key: Core_ICryptographicKey;
begin
sl := TStringList.Create;
try
sl.LoadFromFile(fDataFolder + 'Private.key');
EditKey.Text := sl.Text;
EditKey.Color := clAqua;
KeyMat := TWinRTCryptoHelpers.DecodeFromBase64(sl.Text);
Key := SelectedAlgo.CreateSymmetricKey(KeyMat);
EditKeySize.Text := Key.KeySize.ToString;
finally
sl.Free;
end;
InitWithNewKeys;
end;
{$ENDREGION}
{$REGION 'Symmetric Encrypt/Decryption'}
procedure TFrmSymmetricEncryption.btnEncryptClick(Sender: TObject);
var
Key: Core_ICryptographicKey;
ClearData, Encrypted, IV: IBuffer;
begin
ClearData := TWinRTCryptoHelpers.StrToIBuffer(EditClear.Text);
if SelectAlgoRequiresPadding 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 SelectedAlgo.BlockLength <> 0 then
begin
ShowWarning(
'Message length must be multiple of block length: Message is padded now');
EditClear.Text := EditClear.Text + StringOfChar('_',
SelectedAlgo.BlockLength - ClearData.Length mod SelectedAlgo.BlockLength);
// A better solution would be to use a message length and a random pad
ClearData := TWinRTCryptoHelpers.StrToIBuffer(EditClear.Text);
end;
end;
try
Key := SelectedAlgo.CreateSymmetricKey(
TWinRTCryptoHelpers.DecodeFromBase64(EditKey.Text));
if SelectAlgoRequiresIV then
IV := TCryptographicBuffer.GenerateRandom(SelectedAlgo.BlockLength)
else
IV := nil;
Encrypted := TCore_CryptographicEngine.Encrypt(Key, ClearData, IV);
EditEncrypted.Text := TWinRTCryptoHelpers.EncodeAsBase64(Encrypted);
EditIV.Text := TWinRTCryptoHelpers.EncodeAsBase64(IV);
EditKey.Color := clAqua;
btnSaveEncrypt.Enabled := true;
btnDecrypt.Enabled := true;
except
on e: exception do
ShowError('Encryption failed: ' + e.Message);
end;
end;
procedure TFrmSymmetricEncryption.btnDecryptClick(Sender: TObject);
var
Key: Core_ICryptographicKey;
cleardata, encrypted, IV: IBuffer;
begin
encrypted := TWinRTCryptoHelpers.DecodeFromBase64(EditEncrypted.Text);
IV := TWinRTCryptoHelpers.DecodeFromBase64(EditIV.Text);
try
Key := SelectedAlgo.CreateSymmetricKey(
TWinRTCryptoHelpers.DecodeFromBase64(EditKey.Text));
cleardata := TCore_CryptographicEngine.Decrypt(Key, encrypted, IV);
EditResult.Text := TWinRTCryptoHelpers.IBufferToStr(cleardata);
EditKey.Color := clAqua;
if SameText(EditClear.Text, EditResult.Text) then
ShowResult(
'Passed: Resulting clear text is identical to starting clear text')
else
ShowWarning(
'Failed: Resulting clear text different than starting clear text');
except
on e: exception do
ShowError('Decryption failed: ' + e.Message);
end;
end;
function TFrmSymmetricEncryption.SelectedAlgo: Core_ISymmetricKeyAlgorithmProvider;
// Hint: AesCcm and AesGcm reuqires EncryptAndAuthenticate
var
Algo: HString;
begin
case cboAlgo.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);
end;
function TFrmSymmetricEncryption.SelectKeySizeInBytes: integer;
begin
result := StrToInt(cboKeySize.Text) div 8;
end;
function TFrmSymmetricEncryption.SelectAlgoRequiresPadding: boolean;
begin
result := cboAlgo.ItemIndex in [0, 2]; // Without PKCS #7
end;
function TFrmSymmetricEncryption.SelectAlgoRequiresIV: boolean;
begin
result := cboAlgo.ItemIndex in [0, 1]; // Cbc block cipher mode
end;
{$ENDREGION}
{$REGION 'Encrypted Message Load/Save'}
procedure TFrmSymmetricEncryption.btnSaveEncryptClick(Sender: TObject);
var
sl: TStringList;
begin
sl := TStringList.Create;
try
sl.Add(EditEncrypted.Text);
sl.Add(EditIV.Text);
sl.SaveToFile(fDataFolder + 'Encrypted.txt');
finally
sl.Free;
end;
end;
procedure TFrmSymmetricEncryption.btnLoadEncryptClick(Sender: TObject);
var
sl: TStringList;
begin
sl := TStringList.Create;
try
sl.LoadFromFile(fDataFolder + 'Encrypted.txt');
if sl.Count <> 2 then
raise Exception.Create(
'Format Error: Encrypted text and IV on two lines expected');
EditEncrypted.Text := sl[0];
EditIV.Text := sl[1];
btnDecrypt.Enabled := true;
finally
sl.Free;
end;
end;
{$ENDREGION}
end.