home *** CD-ROM | disk | FTP | other *** search
- {
- Xceed Encryption Library - Memory Encryption Sample
- Copyright (c) 2001 Xceed Software Inc
-
- [unMemEncrypt.pas]
-
- This unit contains the main form's code. It demonstrates how to
- Encrypt a chunk of memory data using different kinds of Encryption methods,
- and how to decrypt encrypted memory data. It specifically uses:
- - The Encrypt, Decrypt, SetSecretKeyFromPassPhrase,
- SetRandomInitVector and SetRandomKeyPair methods.
- - The HasdhingMethod, HashSize, EncryptionMode, PaddingMethod,
- EncryptionMethod, PrivateKey and PublicKey properties.
-
- This file is part of the Xceed Encryption Library sample applications.
- The source code in this file is only intended as a supplment to the Xceed
- Encryption Library's documentation and is provided "as is", without warranty
- of any kind either expressed or implied.
- }
-
- unit unMemEncrypt;
-
- interface
-
- uses
- Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
- ExtCtrls, StdCtrls, XceedEncryptionLib_TLB;
-
- //The different encryption methods
- type TEncryptionMethod = ( eemRijndael, //0
- eemTwoFish ); //1
-
- //The different hashing methods
- type THashingMethod = ( ehmSHA, //0
- ehmHaval ); //1
-
- type
- TfrmMemoryEncrypt = class(TForm)
- grpSymmetricEncryption : TGroupBox;
- grpAsymmetricEncryption : TGroupBox;
- optSymmetricEncryption : TRadioButton;
- optAsymmetricEncryption : TRadioButton;
- Label1 : TLabel;
- Label2 : TLabel;
- Label3 : TLabel;
- Label4 : TLabel;
- Label5 : TLabel;
- edtPassPhrase : TEdit;
- edtPrivateKeyFile : TEdit;
- edtPublicKeyFile : TEdit;
- btOptions : TButton;
- btSelectPrivateKeyFile : TButton;
- btSelectPublicKeyFile : TButton;
- btRandomKeyPair : TButton;
- btEncrypt : TButton;
- btDecrypt : TButton;
- mmoDecryptedText : TMemo;
- mmoEncryptedText : TMemo;
- xOpenDialog: TOpenDialog;
- procedure FormCreate(Sender: TObject);
- procedure btEncryptClick(Sender: TObject);
- procedure btDecryptClick(Sender: TObject);
- procedure btOptionsClick(Sender: TObject);
- procedure btRandomKeyPairClick(Sender: TObject);
- procedure btSelectPublicKeyFileClick(Sender: TObject);
- procedure btSelectPrivateKeyFileClick(Sender: TObject);
- procedure edtPrivateKeyFileExit(Sender: TObject);
- procedure edtPublicKeyFileExit(Sender: TObject);
- procedure optAsymmetricEncryptionClick(Sender: TObject);
- procedure optSymmetricEncryptionClick(Sender: TObject);
- private
- //The values chosen by the user in the options form
- m_eEncryptionMethod : TEncryptionMethod;
- m_eEncryptionMode : EXEEncryptionMode;
- m_ePaddingMethod : EXEPaddingMethod;
- m_eHashingMethod : THashingMethod;
- m_lSecretKeySize : integer;
-
- procedure EnableControls();
- function PrepareEncryptionMethod( var xEncryptor : TXceedEncryption ) : boolean;
- procedure ReadKeyFile( sKeyFile : string; var vaKey : OleVariant );
- procedure SaveEncryptionType();
- procedure SavePrivateKeyFileSetting();
- procedure SavePublicKeyFileSetting();
- public
- { Public declarations }
- end;
-
- var
- frmMemoryEncrypt: TfrmMemoryEncrypt;
-
- implementation
-
- uses unOptions, unKeyPair, unUtility, registry;
-
- {$R *.DFM}
-
- {***************************************************************}
- { }
- { FORM EVENTS }
- { }
- {***************************************************************}
-
- {---------------------------------------------------------------}
- { Initialize the form and some of it's controls }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.FormCreate(Sender: TObject);
- var
- xReg : TRegistryIniFile;
- begin
- mmoDecryptedText.Text := 'This is a little test to show you how the memory ' +
- 'encryption works. And is very easy to use.';
-
- //default value to avoid errors if the options are not set beforehand
- xReg := TRegistryIniFile.Create( 'Software\Xceed\Delphi\MemEncrypt' );
- m_eEncryptionMethod := TEncryptionMethod( xReg.ReadInteger( 'Encryption', 'EncryptionMethod', Ord( eemRijndael ) ) );
- m_eEncryptionMode := xReg.ReadInteger( 'Encryption', 'EncryptionMode', emoFreeBlocks );
- m_ePaddingMethod := xReg.ReadInteger( 'Encryption', 'PaddingMethod', epmFIPS81 );
- m_eHashingMethod := THashingMethod( xReg.ReadInteger( 'Encryption', 'HashingMethod', Ord( ehmSHA ) ) );
- m_lSecretKeySize := xReg.ReadInteger( 'Encryption', 'SecretKeySize', 128 );
- edtPrivateKeyFile.Text := xReg.ReadString( 'Encryption', 'PrivateKeyfile', '' );
- edtPublicKeyFile.Text := xReg.ReadString( 'Encryption', 'PublicKeyFile', '' );
- optAsymmetricEncryption.Checked := xReg.ReadBool( 'Encryption', 'Asymmetric', false );
- optSymmetricEncryption.Checked := xReg.ReadBool( 'Encryption', 'Symmetric', true );
- xReg.Free();
-
- EnableControls();
- end;
-
- {---------------------------------------------------------------}
- { Do the encryption of the original text }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.btEncryptClick(Sender: TObject);
- var
- xEncryptor : TXceedEncryption;
- vaDecryptedText : OleVariant;
- vaEncrypted : OleVariant;
- sHexEncrypted : String;
- begin
- try
- //Create an instance of the Xceed Encryption control
- xEncryptor := TXceedEncryption.Create( self );
- vaDecryptedText := mmoDecryptedText.Text;
-
- //Create an prepare the Encryption Method
- if( PrepareEncryptionMethod( xEncryptor ) ) then
- begin
- //Encrypt the string, specifying that (true parameter) this is the
- //end of the data (there will be no more calls to Encrypt.
- vaEncrypted := xEncryptor.Encrypt( vaDecryptedText, True );
-
- //Display the Encrypted result
- //We convert the binary cipher text to an hexadecimal representation.
- BinaryToHex( vaEncrypted, sHexEncrypted );
-
- // Display the result in the text box
- mmoEncryptedText.Text := sHexEncrypted;
- end;
- except
- on xErr : Exception do
- ShowMessage( 'An error occurred during the encryption process! : ' +
- xErr.Message );
- end;
-
- //Deallocate the Encryption object. The Encryption object will free the
- //EncryptionMethod obeject
- xEncryptor.Free();
- end;
-
- {---------------------------------------------------------------}
- { Do the decryption of the encrypted text }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.btDecryptClick(Sender: TObject);
- var
- xEncryptor : TXceedEncryption;
- vaEncryptedText : OleVariant;
- vaDecrypted : OleVariant;
- begin
- try
- //Create an instance of the Xceed Encryption Library
- xEncryptor := TXceedEncryption.Create( self );
-
- //Create an prepare the Encryption Method
- if( PrepareEncryptionMethod( xEncryptor ) ) then
- begin
- mmoDecryptedText.Clear();
-
- HexToBinary( mmoEncryptedText.Text, vaEncryptedText );
-
- //Decrypt the Encrypted string, specifying that (True parameter)
- //this is the end of the data (there will be no more calls to Decrypt)
-
- vaDecrypted := xEncryptor.Decrypt( vaEncryptedText, True );
-
- if( VarIsEmpty( vaDecrypted ) ) then
- //No output was produced
- mmoDecryptedText.Text := ''
- else
- //Display the Decrypted result
- mmoDecryptedText.Clear();
- mmoDecryptedText.Text := vaDecrypted;
- end;
- except
- on xErr : Exception do
- ShowMessage( 'Error during Decryption process! : ' + xErr.Message );
- end;
- xEncryptor.Free();
- end;
-
- {---------------------------------------------------------------}
- { Display the Options form, saving them if the user clicks OK }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.btOptionsClick(Sender: TObject);
- var
- xOptionsForm : TfrmOptions;
- xReg : TRegistryIniFile;
- begin
- xOptionsForm := TfrmOptions.Create( self );
-
- if xOptionsForm.ShowForm( m_eEncryptionMethod, m_eEncryptionMode,
- m_ePaddingMethod, m_eHashingMethod,
- m_lSecretKeySize ) then
- begin
- xReg := TRegistryIniFile.Create( 'Software\Xceed\Delphi\MemEncrypt' );
- xReg.WriteInteger( 'Encryption', 'EncryptionMethod', Ord( m_eEncryptionMethod ) );
- xReg.WriteInteger( 'Encryption', 'EncryptionMode', Ord( m_eEncryptionMode ) );
- xReg.WriteInteger( 'Encryption', 'PaddingMethod', Ord( m_ePaddingMethod ) );
- xReg.WriteInteger( 'Encryption', 'HashingMethod', Ord( m_eHashingMethod ) );
- xReg.WriteInteger( 'Encryption', 'SecretKeySize', Ord( m_lSecretKeySize ) );
- xReg.Free();
- end;
-
- xOptionsForm.Free();
- end;
-
- {---------------------------------------------------------------}
- { Generate new private and public keys stored in the file }
- { specified in the respective edit boxes }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.btRandomKeyPairClick(Sender: TObject);
- var
- xKeyPairForm : TfrmKeyPair;
- begin
- //The file names are mandatory!!!!
- if( length( trim( edtPrivateKeyFile.Text ) ) = 0 ) or ( length( trim( edtPublicKeyFile.Text ) ) = 0 ) then
- ShowMessage( 'You must specify the key file names where the public and ' +
- 'private keys will be stored!!' )
- else
- begin
- //Show the dialog box used to generate a nre key pair, passing
- //it the 2 file names.
- xKeyPairForm := TfrmKeyPair.Create( self );
- xKeyPairForm.ShowForm( edtPrivateKeyFile.Text, edtPublicKeyFile.Text );
- xKeyPairForm.Free();
- end;
- end;
-
- {---------------------------------------------------------------}
- { Select the file name that contains (or will contain) the }
- { private key }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.btSelectPrivateKeyFileClick(Sender: TObject);
- begin
- xOpenDialog.Files.Clear();
- xOpenDialog.Title := 'Source File';
- xOpenDialog.Filter := 'Key File (*.key)|*.key|All Type (*.*)|*.*';
- xOpenDialog.FilterIndex := 0;
-
- if( xOpenDialog.Execute ) then
- begin
- if( length( xOpenDialog.Files.Text ) > 0 )then
- edtPrivateKeyFile.Text := trim( xOpenDialog.Files.Text );
- SavePrivateKeyFileSetting();
- end;
- end;
-
- {---------------------------------------------------------------}
- { Select the file that contains (or will contain) the public key}
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.btSelectPublicKeyFileClick(Sender: TObject);
- begin
- xOpenDialog.Files.Clear();
- xOpenDialog.Title := 'Source File';
- xOpenDialog.Filter := 'Key File (*.key)|*.key|All Type (*.*)|*.*';
- xOpenDialog.FilterIndex := 0;
-
- if( xOpenDialog.Execute ) then
- begin
- if( length( xOpenDialog.Files.Text ) > 0 ) then
- edtPublicKeyFile.Text := trim( xOpenDialog.Files.Text );
- SavePublicKeyFileSetting();
- end;
- end;
-
- {---------------------------------------------------------------}
- { The user exited the private key file text box. Save the }
- { modification. }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.edtPrivateKeyFileExit(Sender: TObject);
- begin
- SavePrivateKeyFileSetting();
- end;
-
- {---------------------------------------------------------------}
- { The user exited the public key file text box. Save the }
- { modification. }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.edtPublicKeyFileExit(Sender: TObject);
- begin
- SavePublicKeyFileSetting();
- end;
-
- {---------------------------------------------------------------}
- { The user selected asymmetric mode, disable controls }
- { associated with symmetric encryption }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.optAsymmetricEncryptionClick(Sender: TObject);
- begin
- if( self.visible ) then
- begin
- optSymmetricEncryption.Checked := false;
- EnableControls();
- SaveEncryptionType();
- end;
- end;
-
- {---------------------------------------------------------------}
- { The user selected symmetric mode, disable controls associated }
- { with asymmetric encryption. }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.optSymmetricEncryptionClick(Sender: TObject);
- begin
- if( self.Visible ) then
- begin
- optAsymmetricEncryption.Checked := false;
- EnableControls();
- SaveEncryptionType();
- end;
- end;
-
- {***************************************************************}
- { }
- { FORM FUNCTIONS AND PROCEDURES }
- { }
- {***************************************************************}
-
- {---------------------------------------------------------------}
- { Enable the control associated with the selected encryption }
- { type (symmetric or asymmetric). Disable the other controls. }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.EnableControls();
- var
- bSecretKeyEncryption : boolean;
- begin
- bSecretKeyEncryption := optSymmetricEncryption.Checked;
-
- edtPassPhrase.Enabled := bSecretKeyEncryption;
- btOptions.Enabled := bSecretKeyEncryption;
- edtPrivateKeyFile.Enabled := not bSecretKeyEncryption;
- btSelectPrivateKeyFile.Enabled := not bSecretKeyEncryption;
- edtPublicKeyFile.Enabled := not bSecretKeyEncryption;
- btSelectPublicKeyFile.Enabled := not bSecretKeyEncryption;
- btRandomKeyPair.Enabled := not bSecretKeyEncryption;
- end;
-
- {---------------------------------------------------------------}
- { Prepare the encryption method according to the user selection }
- { Return true if all succeeded }
- {---------------------------------------------------------------}
- function TfrmMemoryEncrypt.PrepareEncryptionMethod( var xEncryptor : TXceedEncryption ) : boolean;
- //We use on variable for each encryption method to simplify the
- //programming. Only one of these will be used at a time (according to the
- //user selected Encryption Method.
- var
- xRijndael : DXceedRijndaelEncryptionMethod;
- xTwoFish : DXceedTwofishEncryptionMethod;
- xRSA : DXceedRSAEncryptionMethod;
- xHaval : DXceedHavalHashingMethod;
- xSHA : DXceedSHAHashingMethod;
- vaPrivateKey : OleVariant;
- vaPublicKey : OleVariant;
- bPrepareOk : boolean;
- begin
- bPrepareOk := true;
- try
- if optSymmetricEncryption.Checked then
- begin
- //the user chose to perform symmetric encryption/decryption
-
- case m_eEncryptionMethod of
- eemRijndael : begin
- //Instantiate the Rijndael encryption method
- xRijndael := CoXceedRijndaelEncryptionMethod.Create();
-
- //Set the hashing method that will be used to set the
- //key from the pass phrase
- case m_eHashingMethod of
- ehmHaval : begin
- xHaval := CoXceedHavalHashingMethod.Create();
- //Haval supports hash sizes equivalent to the
- //supported key size. So we can assign the latter
- //to the former without problem.
- xHaval.HashSize := m_lSecretKeySize;
- xRijndael.HashingMethod := xHaval;
- end;
- ehmSHA : begin
- xSHA := CoXceedSHAHashingMethod.Create();
-
- //We arbitarily set the HashSize to the maximum
- //key size allowed so we don't have to worry that
- //the hash result of the pass phrase could be shorter
- //than the expected key (although the Xceed Encryption
- //Library would have dealt with it).
- xSHA.HashSize := 256;
- xRijndael.HashingMethod := xSHA;
- end;
- end;
-
- //Set the encryption mode
- xRijndael.EncryptionMode := m_eEncryptionMode;
-
- //Set the padding method (for the last encrypted and decrypted block)
- xRijndael.PaddingMethod := m_ePaddingMethod;
-
- //Set the secret key of the desired size using the user pass phrase
- xRijndael.SetSecretKeyFromPassPhrase( edtPassPhrase.Text, m_lSecretKeySize );
-
- if ( m_eEncryptionMode = emoChainedBlocks ) then
- //Will be useful only when encryptin since, in decrption,
- //the InitVector is read at the beginning of the
- //encrypted text.
- xRijndael.SetRandomInitVector();
-
- //Set the previously initialized encryption method
- //of the Encryptor object received as a parameter
- //of this function
- xEncryptor.EncryptionMethod := xRijndael;
- end;
-
- eemTwoFish : begin
- //Intantiate the TwoFish encryption method
- xTwoFish := CoXceedTwofishEncryptionMethod.Create();
-
- case m_eHashingMethod of
- ehmHaval : begin
- xHaval := CoXceedHavalHashingMethod.Create();
- xHaval.HashSize := m_lSecretKeySize;
- xTwoFish.HashingMethod := xHaval;
- end;
- ehmSHA : begin
- xSHA := CoXceedSHAHashingMethod.Create();
- xSHA.HashSize := 256;
- xTwoFish.HashingMethod := xSHA;
- end;
- end;
-
- xTwoFish.EncryptionMode := m_eEncryptionMode;
- xTwoFish.PaddingMethod := m_ePaddingMethod;
- xTwoFish.SetSecretKeyFromPassPhrase( edtPassPhrase.Text, m_lSecretKeySize );
-
- if( m_eEncryptionMode = emoChainedBlocks ) then
- xTwoFish.SetRandomInitVector();
-
- xEncryptor.EncryptionMethod := xTwoFish;
- end;
- end;
- end;
-
- //The user chose to perform asymmetric encryption/decryption
- if optAsymmetricEncryption.Checked then
- begin
- //instantiate the RSA encryption method
- xRSA := CoXceedRSAEncryptionMethod.Create();
-
- //Initialize the private key (used when decrypting)
- ReadKeyFile( edtPrivateKeyFile.Text, vaPrivateKey );
- xRSA.Set_PrivateKey( vaPrivateKey );
-
- //Initialize the public key (used when encrypting)
- ReadKeyFile( edtPublicKeyFile.Text, vaPublicKey );
- xRSA.Set_PublicKey( vaPublicKey );
-
- xEncryptor.EncryptionMethod := xRSA;
- end;
- except
- on xErr : Exception do
- begin
- bPrepareOk := false;
- ShowMessage( 'Error during EncryptionMethod initialization! : ' +
- xErr.Message );
- end;
- end;
- PrepareEncryptionMethod := bPrepareOk;
- end;
-
- {---------------------------------------------------------------}
- { Read the content of the specified file. Allegedly containing }
- { a private or public key. Return the key in the vaKey }
- { parameter. }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.ReadKeyFile( sKeyFile : string;
- var vaKey : OleVariant );
- var
- xFile : TextFile;
- sKey : string;
- pData : Char;
- begin
- vaKey := varEmpty;
- if( length( sKeyFile ) > 0 )then
- begin
- AssignFile( xFile, sKeyFile );
- Reset( xFile );
- sKey := '';
-
- while not EOF( xFile ) do
- begin
- Read( xFile, pData );
- sKey := sKey + pData;
- end;
- CloseFile( xFile );
-
- HexToBinary( sKey, vaKey );
- end;
- end;
-
- {---------------------------------------------------------------}
- { Save the current selected (and deselected) encryption type }
- { (symmetric or asymmetric) }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.SaveEncryptionType();
- var
- xReg : TRegistryIniFile;
- begin
- xReg := TRegistryIniFile.Create( 'Software\Xceed\Delphi\MemEncrypt' );
- xReg.WriteBool( 'Encryption', 'Asymmetric', optAsymmetricEncryption.Checked );
- xReg.WriteBool( 'Encryption', 'Symmetric', optSymmetricEncryption.Checked );
- xReg.Free();
- end;
-
- {---------------------------------------------------------------}
- { Save the current private key file name }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.SavePrivateKeyFileSetting();
- var
- xReg : TRegistryIniFile;
- begin
- xReg := TRegistryIniFile.Create( 'Software\Xceed\Delphi\MemEncrypt' );
- xReg.WriteString( 'Encryption', 'PrivateKeyFile', edtPrivateKeyFile.Text );
- xReg.Free();
- end;
-
- {---------------------------------------------------------------}
- { Save the current public key file name }
- {---------------------------------------------------------------}
- procedure TfrmMemoryEncrypt.SavePublicKeyFileSetting();
- var
- xReg : TRegistryIniFile;
- begin
- xReg := TRegistryIniFile.Create( 'Software\Xceed\Delphi\MemEncrypt' );
- xReg.WriteString( 'Encryption', 'PublicKeyFile', edtPublicKeyFile.Text );
- xReg.Free();
- end;
-
- end.
-
-