Skip to content

Commit 62609f1

Browse files
committed
Improved/added further comments
1 parent c50332d commit 62609f1

File tree

1 file changed

+74
-9
lines changed

1 file changed

+74
-9
lines changed

Demos/Cipher_FMX/MainFormCipherFMX.pas

Lines changed: 74 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ TFormMain = class(TForm)
198198
/// Get the clipboard instance to be able to put something in it
199199
/// </summary>
200200
/// <param name="Clipboard">
201-
/// If successfull the aquired clipboard object
201+
/// The aquired clipboard object, if successfull
202202
/// </param>
203203
/// <returns>
204204
/// true if the clipboard instance could be aquired
@@ -250,7 +250,8 @@ function TFormMain.TryGetClipboardService(out Clipboard: IFMXClipboardService):
250250
begin
251251
Result := TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService);
252252
if Result then
253-
Clipboard := IFMXClipboardService(TPlatformServices.Current.GetPlatformService(IFMXClipboardService));
253+
Clipboard := IFMXClipboardService(
254+
TPlatformServices.Current.GetPlatformService(IFMXClipboardService));
254255
end;
255256

256257
procedure TFormMain.StringToClipboard(const s: string);
@@ -267,13 +268,20 @@ procedure TFormMain.ButtonCreateKeyClick(Sender: TObject);
267268
Context : TCipherContext;
268269
RandBytes: TBytes;
269270
begin
270-
Assert(ComboBoxCipherAlgorithm.ItemIndex >= 0, 'No algo selected');
271-
KeyFormat := TDECFormat.ClassByName(ComboBoxKeyIVFormat.Items[ComboBoxKeyIVFormat.ItemIndex]);
271+
Assert(ComboBoxCipherAlgorithm.ItemIndex >= 0, 'No cipher algorithm selected');
272+
// creates a randomized encryption/decryption key in the key format selected
272273

274+
// Determinhe the selected key format
275+
KeyFormat := TDECFormat.ClassByName(
276+
ComboBoxKeyIVFormat.Items[ComboBoxKeyIVFormat.ItemIndex]);
277+
// This failed. It should not happen though, because all formats should be registered
273278
Assert(Assigned(KeyFormat), 'Missing format');
279+
280+
// Get metadata for the selected encryption algorithm. We need the key length
274281
Context := TDECCipher.ClassByName(
275282
ComboBoxCipherAlgorithm.Items[ComboBoxCipherAlgorithm.ItemIndex]).Context;
276-
283+
// Create a random key using DEC's pseudo random number generator and write the
284+
// formatted output into the edit
277285
RandBytes := RandomBytes(Context.KeySize);
278286
EditKey.Text := StringOf(KeyFormat.Encode(RandBytes));
279287
end;
@@ -285,12 +293,27 @@ procedure TFormMain.ButtonCreateIVClick(Sender: TObject);
285293
RandBytes: TBytes;
286294
begin
287295
Assert(ComboBoxCipherAlgorithm.ItemIndex >= 0, 'No algo selected');
296+
// Creates a randomized initialization vector. That is one possible way to
297+
// generate an initialization vector IV. The IV should be a new and unique
298+
// value for each use of the encryption algorithm. It may be stored along
299+
// with the encrypted data as it is needed by the receiver to decrypt the
300+
// data. Not using a unique value for this is a security problem as it makes
301+
// cracking the encryption easier. When decrypting data the very same IV which
302+
// was used for encrypting the data needs to be set as IV, so this button is
303+
// useless in decryption scenarios! The filler byte one can specify is used to
304+
// fill up any IV which is shorter than the length of the encryption key.
305+
306+
// Determine the selected IV format
288307
IVFormat := TDECFormat.ClassByName(ComboBoxKeyIVFormat.Items[ComboBoxKeyIVFormat.ItemIndex]);
289308

290309
Assert(Assigned(IVFormat), 'Missing format');
310+
// get meta data for the encryption/decryption algorithm used. The lenght of
311+
// the IV usually matches the length of the encryption key
291312
Context := TDECCipher.ClassByName(
292313
ComboBoxCipherAlgorithm.Items[ComboBoxCipherAlgorithm.ItemIndex]).Context;
293314

315+
// Create a random IV using DEC's pseudo random number generator and write the
316+
// formatted output into the edit
294317
RandBytes := RandomBytes(Context.BlockSize);
295318
EditInitVector.Text := StringOf(IVFormat.Encode(RandBytes));
296319
end;
@@ -299,13 +322,16 @@ procedure TFormMain.ButtonCopyClick(Sender: TObject);
299322
var
300323
s : string;
301324
begin
325+
// Copy entered data into the clipboard
302326
s := '//start' + sLineBreak +
303327
'Cipher: ' +
304328
ComboBoxCipherAlgorithm.Items[ComboBoxCipherAlgorithm.ItemIndex] +
305329
sLineBreak +
306330
'Mode: ' +
307331
ComboBoxChainingMethod.Items[ComboBoxChainingMethod.ItemIndex] +
308332
sLineBreak +
333+
'Padding mode: ' + ComboBoxPaddingMode.Items[ComboBoxPaddingMode.ItemIndex] +
334+
sLineBreak +
309335
'Key: ' + EditKey.Text + sLineBreak +
310336
'Init vector: ' + EditInitVector.Text + sLineBreak +
311337
'Filler: ' + EditFiller.Text + sLineBreak +
@@ -337,10 +363,14 @@ procedure TFormMain.ButtonDecryptClick(Sender: TObject);
337363
AuthenticationOK : Boolean; // for authenticated ciphers: is the calculated
338364
// authentication result value correct?
339365
begin
366+
// Decrypts the entered encrypted data using the settings made
367+
368+
// Determine desired output format
340369
if not GetFormatSettings(PlainTextFormatting, CipherTextFormatting) then
341370
exit;
342371

343372
try
373+
// Create an instance for the cypher used to decrypt and initialize its properties
344374
Cipher := GetInitializedCipherInstance;
345375

346376
try
@@ -353,16 +383,18 @@ procedure TFormMain.ButtonDecryptClick(Sender: TObject);
353383
AuthenticationOK := false;
354384

355385
try
386+
// the real decryption
356387
CipherTextBuffer := CipherTextFormatting.Decode(CipherTextBuffer);
357388
LabelLenChiffreText.Text := Format('Buffer: %d bytes, Formatted: %d chars',
358389
[length(CipherTextBuffer), length(EditCipherText.Text)]);
359390

360391
PlainTextBuffer := (Cipher as TDECFormattedCipher).DecodeBytes(CipherTextBuffer);
392+
361393
// in case of an authenticated cipher mode like cmGCM the Done method
362394
// will raise an exception when the calculated authentication value does
363395
// not match the given expected one set in SetAuthenticationParams().
364-
365396
(Cipher as TDECFormattedCipher).Done;
397+
366398
// If we managed to get to here, the calculated authentication value is
367399
// ok if we're in an authenticated mode and have entered an expected value.
368400
if (length(EditExpectedAuthenthicationResult.Text) > 0) and
@@ -383,6 +415,7 @@ procedure TFormMain.ButtonDecryptClick(Sender: TObject);
383415

384416
if Cipher.IsAuthenticated then
385417
begin
418+
// Display calculated authentication value
386419
EditCalculatedAuthenticationValue.Text :=
387420
StringOf(TFormat_HEXL.Encode(Cipher.CalculatedAuthenticationResult));
388421

@@ -391,6 +424,8 @@ procedure TFormMain.ButtonDecryptClick(Sender: TObject);
391424
TMsgDlgType.mtInformation);
392425
end;
393426

427+
// Transform decrypted data into the requested display/output format
428+
// and display it
394429
EditPlainText.Text := DECUtil.BytesToString(PlainTextFormatting.Encode(PlainTextBuffer));
395430
LabelLenPlainText.Text := Format('Buffer: %d bytes, Formatted: %d chars',
396431
[length(PlainTextBuffer), length(EditPlainText.Text)]);
@@ -401,13 +436,18 @@ procedure TFormMain.ButtonDecryptClick(Sender: TObject);
401436
TextFailed.Visible := false;
402437
end
403438
else
439+
// We have remembered the last enetered plain text and can compare
440+
// with that. This can be used to demo that this plain text I just
441+
// encrypted wa sproperly decrypted in my immediate decryption demo
404442
if FLastEncryptedPlainText = EditPlainText.Text then
405443
begin
406444
TextPassed.Visible := true;
407445
TextFailed.Visible := false;
408446
end
409447
else
410448
begin
449+
// The demo failed, most likely because the decryption was done on
450+
// something else than the encryption of that last used plain text
411451
TextPassed.Visible := false;
412452
TextFailed.Visible := true;
413453
end;
@@ -438,6 +478,7 @@ procedure TFormMain.ButtonEncryptClick(Sender: TObject);
438478
exit;
439479

440480
try
481+
// Create an instance for the cypher used to encrypt and initialize its properties
441482
Cipher := GetInitializedCipherInstance;
442483

443484
try
@@ -446,16 +487,19 @@ procedure TFormMain.ButtonEncryptClick(Sender: TObject);
446487
else
447488
InputBuffer := DECUtil.RawStringToBytes(RawByteString(EditPlainText.Text));
448489

490+
// Check if the data to be encrypted matches the selected format
449491
if InputFormatting.IsValid(InputBuffer) then
450492
begin
451493
// Set all authentication related properties
452494
SetAuthenticationParams(Cipher);
453495

454496
try
497+
// transform the text to be encrypted from the format given into a byte buffer
455498
InputBuffer := InputFormatting.Decode(InputBuffer);
456499
LabelLenPlainText.Text := Format('Buffer: %d bytes, Formatted: %d chars',
457500
[length(InputBuffer), length(EditPlainText.Text)]);
458501

502+
// Perform the actual encryption
459503
OutputBuffer := (Cipher as TDECFormattedCipher).EncodeBytes(InputBuffer);
460504
(Cipher as TDECFormattedCipher).Done;
461505
FLastEncryptedPlainText := EditPlainText.Text;
@@ -465,10 +509,14 @@ procedure TFormMain.ButtonEncryptClick(Sender: TObject);
465509
TMsgDlgType.mtError);
466510
end;
467511

468-
EditCipherText.Text := string(DECUtil.BytesToRawString(OutputFormatting.Encode(OutputBuffer)));
512+
// display the encrypted text in the selected output format
513+
EditCipherText.Text := string(DECUtil.BytesToRawString(
514+
OutputFormatting.Encode(OutputBuffer)));
469515
LabelLenChiffreText.Text := Format('Buffer: %d bytes, Formatted: %d chars',
470516
[length(OutputBuffer), length(EditCipherText.Text)]);
471517

518+
// If the algorithm is an authenticated cipher display the calculated
519+
// authentication value
472520
if Cipher.IsAuthenticated then
473521
EditCalculatedAuthenticationValue.Text :=
474522
StringOf(TFormat_HEXL.Encode(Cipher.CalculatedAuthenticationResult));
@@ -498,6 +546,7 @@ procedure TFormMain.ComboBoxKeyIVFormatChange(Sender: TObject);
498546
NewFormat: TDECFormatClass;
499547
Raw : RawByteString;
500548
begin
549+
// determine the desired input format for the initialization vector IV
501550
NewFormat := TDECFormat.ClassByName(
502551
ComboBoxKeyIVFormat.Items[ComboBoxKeyIVFormat.ItemIndex]);
503552

@@ -534,6 +583,7 @@ procedure TFormMain.ComboBoxKeyIVFormatChange(Sender: TObject);
534583

535584
procedure TFormMain.EditPlainCipherTextChangeTracking(Sender: TObject);
536585
begin
586+
// when plain text changed hide some labels related to authentication result
537587
TextPassed.Visible := false;
538588
TextFailed.Visible := false;
539589
end;
@@ -542,6 +592,7 @@ procedure TFormMain.ComboBoxCipherAlgorithmChange(Sender: TObject);
542592
var
543593
Context : TCipherContext;
544594
begin
595+
// if a different cipher algorithm is selected update the displayed meta data
545596
Context := TDECCipher.ClassByName(
546597
ComboBoxCipherAlgorithm.Items[ComboBoxCipherAlgorithm.ItemIndex]).Context;
547598

@@ -582,6 +633,8 @@ procedure TFormMain.FormCreate(Sender: TObject);
582633
var
583634
AppService : IFMXApplicationService;
584635
begin
636+
// Display program version fetched from the binary. The platform service
637+
// only supports a shorter format.
585638
if TPlatformServices.Current.SupportsPlatformService(IFMXApplicationService,
586639
IInterface(AppService)) then
587640
LabelVersion.Text := format(LabelVersion.Text, [AppService.AppVersion])
@@ -620,6 +673,7 @@ procedure TFormMain.InitPaddingModesCombo;
620673
var
621674
PaddingMode: TPaddingMode;
622675
begin
676+
// add all available padding modes to the combo box
623677
ComboBoxPaddingMode.Clear;
624678

625679
for PaddingMode := low(TPaddingMode) to high(TPaddingMode) do
@@ -674,6 +728,9 @@ function TFormMain.GetInitializedCipherInstance: TDECCipherModes;
674728
KeyIVFormat: TDECFormatClass;
675729
FillerByte : UInt8;
676730
begin
731+
// Get data from the user input or where it is missing define some
732+
733+
// Initialization vector IV fill up byte for too short vectors entered
677734
if not EditFiller.Text.IsEmpty then
678735
begin
679736
while length(EditFiller.Text) < 2 do
@@ -685,13 +742,17 @@ function TFormMain.GetInitializedCipherInstance: TDECCipherModes;
685742
// we need to assume something to be able to call that init overload
686743
FillerByte := 0;
687744

745+
// get selected input format for IV
688746
KeyIVFormat := TDECFormat.ClassByName(
689747
ComboBoxKeyIVFormat.Items[ComboBoxKeyIVFormat.ItemIndex]);
690748
Assert(Assigned(KeyIVFormat), 'Missing format');
691749

750+
// Check entered IV for format/syntax validity
692751
if KeyIVFormat.IsValid(RawByteString(EditInitVector.Text)) and
693752
KeyIVFormat.IsValid(RawByteString(EditKey.Text)) then
694753
begin
754+
// Create instance of the cipher algorithm and initialize it using key, IV
755+
// and padding mode given by the user
695756
Result := GetCipherInstance;
696757
Result.Init(RawStringToBytes(KeyIVFormat.Decode(RawByteString(EditKey.Text))),
697758
RawStringToBytes(KeyIVFormat.Decode(RawByteString(EditInitVector.Text))),
@@ -705,21 +766,23 @@ function TFormMain.GetSelectedCipherMode: TCipherMode;
705766
var
706767
ModeStr : string;
707768
begin
769+
// Display value of the selected block concatenation mode
708770
ModeStr := ComboBoxChainingMethod.Items[ComboBoxChainingMethod.ItemIndex];
709771

772+
// remove things only present for display purposes
710773
if ModeStr.Contains('(') then
711774
ModeStr := ModeStr.Remove(ModeStr.IndexOf('(')-1);
712775

713776
// Determine selected block chaining method via RTTI (runtime type information)
714777
Result := TCipherMode(System.TypInfo.GetEnumValue(
715-
TypeInfo(TCipherMode),
716-
ModeStr));
778+
TypeInfo(TCipherMode), ModeStr));
717779
end;
718780

719781
function TFormMain.GetSelectedPaddingMode: TPaddingMode;
720782
var
721783
ModeStr : string;
722784
begin
785+
// Display value of the selected padding mode (filling up a last incomplete block)
723786
ModeStr := ComboBoxPaddingMode.Items[ComboBoxPaddingMode.ItemIndex];
724787
// Determine selected block chaining method via RTTI (runtime type information)
725788
Result := TPaddingMode(System.TypInfo.GetEnumValue(TypeInfo(TPaddingMode),
@@ -731,6 +794,7 @@ procedure TFormMain.InitCipherCombo;
731794
MyClass : TPair<Int64, TDECClass>;
732795
Ciphers : TStringList;
733796
begin
797+
// List all registered ciphers in the combobox
734798
Ciphers := TStringList.Create;
735799

736800
try
@@ -757,6 +821,7 @@ procedure TFormMain.InitCipherModes;
757821
CipherMode : TCipherMode;
758822
Name : string;
759823
begin
824+
// List all available block chaining modes in the combobox
760825
ComboBoxChainingMethod.Clear;
761826
for CipherMode := low(TCipherMode) to high(TCipherMode) do
762827
begin

0 commit comments

Comments
 (0)