Encrypting a file with 3DES

http://lockbox.seanbdurkin.id.au/Encrypt+a+file

n this tutorial, we are going to use a component based approach to encrypt some files.

Make a new VCL Forms Application. Name the main form as mfmWestwood3DES_Tut, and save the unit as umfmWestwood3DES_Tut and the project as Westwood3DES_Tut. Save the project and all files in a directory. Set the main form caption if you like.

On the main form, add a button (btnEncrypt) with caption "Encrypt" in the top left hand corner. This button will encrypt a file.

Add a memo box underneath (memoLog) filling out most of the remainder of the client area. Set its anchors to all sides. Set it Read-only, and turn on the vertical scroll bar.

Go to the LockBox palette and slap down a TCodec component and hook it up to a TCryptographicLibrary component.

The main form should look like this (click to expand)
For Westwood's 3DES demo

The text of the View-As-Form should look something like this…

object mfmWestwood3DES_Tut: TmfmWestwood3DES_Tut
  Left = 0
  Top = 0
  Caption = 'Westwood 3DES Tutorial'
  ClientHeight = 294
  ClientWidth = 562
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  DesignSize = (
    562
    294)
  PixelsPerInch = 96
  TextHeight = 13
  object btnEncrypt: TButton
    Left = 8
    Top = 8
    Width = 75
    Height = 25
    Caption = 'Encrypt'
    TabOrder = 0
  end
  object memoLog: TMemo
    Left = 8
    Top = 39
    Width = 546
    Height = 247
    Anchors = [akLeft, akTop, akRight, akBottom]
    Color = clInfoBk
    Lines.Strings = (
      '[Log output will go here.]')
    ScrollBars = ssVertical
    TabOrder = 1
  end
  object Codec1: TCodec
    AsymetricKeySizeInBits = 1024
    AdvancedOptions2 = []
    CryptoLibrary = CryptographicLibrary1
    Left = 160
    Top = 104
    StreamCipherId = ''
    BlockCipherId = ''
    ChainId = ''
  end
  object CryptographicLibrary1: TCryptographicLibrary
    Left = 272
    Top = 104
  end
end


 

Nice start! Ok, lets set up the Codec.

On the TCodec component, lets have a look at the ChainMode property.
Let's try ECB. Select ECB (it will appear in a pull-down, listed as "ECB (with block padding)").
Then click on the component "About…" property to bring up the About box. Go the the last tab "Algorithms". Look at the bottom left hand pane "About Selected Chaining Mode" to find the attributes (and some-times design notes) about the selected Chaining Mode (ECB in this case).

About box and chaining mode (Click to expand)

One features says (afCryptographicallyWeak) says that this chaining mode (ECB) is considered cryptographically weak. There is a link below the features list, to a wikipedia page explaining why. Some projects may be constrained to ECB due to interoperability requirements or non-technical requirements. But if not, as we will assume in this demo, it is better to choose another Chaining mode.

Thus having been warned, change the ChainMode property to CBC. There is nothing wrong with CBC. It is a good old favourite.
Now lets look at the other properties..

AsymetricKeySize doesnt concern us, because it is only of consequence for asymetric ciphers like RSA. This tutorial is about symetric ciphers.

For the Cipher property, choose 3DES (keying option 1). To understand the difference between keying option 1 and option 2, read the wikipedia pages linked in the About Box, once the cipher is selected.

As a point of interest, in this tutorial, we are setting these properties at design-time, but we could equally well do them at run-time. The single design-time published property "Cipher" is equivalent to the pair of run-time public properties StreamCipherID and BlockCipherID.
 

General demonstration support

Add a method to display text to the user like so …

procedure TmfmWestwood3DES_Tut.Put(
  const Line: string; const Args: array of const);
begin
memoLog.Lines.Add( Format( Line, Args))
end;

Implement an OnCreate event handler for the main form to set the password and do normal program start-up stuff like so ….

const
  Password = 'Banana-rover';

procedure TmfmWestwood3DES_Tut.FormCreate(Sender: TObject);
begin
Codec1.Password := Password;
memoLog.Clear;
Put( 'Press the ''Encrypt'' buton to encrypt a file with 3-DES (keying option 1)', []);
end;


 

And now the meat

Add two TOpenDialog components to the form with names dlgOpenPlaintext and dlgOpenCiphertext. These dialog components will be used to select the plaintext file to encrypt and the ciphertext file to decrypt.
Set the title property and the options of these dialogs as required. For example you could set the title of dlgOpenPlaintext to 'Select plaintext file', and the Options to Options = ofReadOnly, ofHideReadOnly, ofFileMustExist, ofEnableSizing]

Now let's add the event handler for the "Encrypt" button like so …

procedure TmfmWestwood3DES_Tut.btnEncryptClick( Sender: TObject);
var
  sPlaintextFN, sCiphertextFN: string;
begin
if not dlgOpenPlaintext.Execute then exit;
try
  Put( '', []);
  sPlaintextFN  := dlgOpenPlaintext.FileName;
  sCiphertextFN := sPlaintextFN + '.enc';
  Codec1.EncryptFile( sPlaintextFN, sCiphertextFN);
  Put( 'The file "%s" was encrypted with 3DES-K1/CBC. The encrypted output was stored in file "%s".',
    [sPlaintextFN, sCiphertextFN])
except on E: Exception do
    begin
    Put( '%s: %s', [E.ClassName, E.Message]);
    Codec1.Reset
    end
  end;
end;

This is the meat of the tutorial. Some points to note are:

  • This button can be fired repeatedly. The password, cipher and chain mode only need to be set once, not once per encryption operation.
  • If an exception offucred (for example because of a device i/o error or the file did not exist, make sure to call Reset.


Decryption is similar. Use another button for it and implement like this…
 

procedure TmfmWestwood3DES_Tut.btnDecryptClick( Sender: TObject);
var
  sPlaintextFN, sCiphertextFN: string;
begin
if not dlgOpenCiphertext.Execute then exit;
try
  Put( '', []);
  sCiphertextFN  := dlgCipherPlaintext.FileName;
  sPlaintextFN   := sPlaintextFN + '.recon';
  Codec1.DecryptFile( sPlaintextFN, sCiphertextFN);
  Put( 'The file "%s" was decrypted with 3DES-K1/CBC. The deccrypted output was stored in file "%s".',
    [sCiphertextFN, sPlaintextFN])
except on E: Exception do
    begin
    Put( '%s: %s', [E.ClassName, E.Message]);
    Codec1.Reset
    end
  end;
end;

Try running the program. Encrypt a file and then decrypt the encrypted (.enc) file. Compare the reconstructed plaintext file (.recon) with the original file. It should be the same.

This concludes our tutorial on encryption with 3-DES.

Happy Cryptography!
This tutorial continues with the subject of Hash something

 

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享