home *** CD-ROM | disk | FTP | other *** search
/ Chip 2002 September / Chip_2002-09_cd1.bin / zkuste / vbasic / Data / Utils / XZipComp.exe / XceedEncryption.Cab / F112939_unManager.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  2001-07-04  |  19.0 KB  |  472 lines

  1. {
  2.  Xceed Encryption Library - Encryption Manager sample
  3.  Copyright (c) 2001 Xceed Software Inc.
  4.  
  5.  [unManager.pas]
  6.  
  7.  This unit contains the main form's code. It demonstrates how to encrypt
  8.  a file using different encryption methods and how to decrypt an encrypted
  9.  file. It specifically uses:
  10.   - The ProcessFile, SetSecretKeyFromPassPhrase and SetRandomInitVector methods.
  11.   - The EncryptionMethod, PaddingMethod and HashingMethod properties.
  12.  
  13.   This file is part of the Xceed Encryption Library sample applications.
  14.   The source code in this file is only intended as a supplement to the Xceed
  15.   Encryption Library's documentation and is provided "as is" without warranty
  16.   of any kind, either expressed or implied.
  17. }
  18.  
  19. unit unManager;
  20.  
  21. interface
  22.  
  23. uses
  24.   Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  25.   StdCtrls, XceedEncryptionLib_TLB, Menus;
  26.  
  27. //The different encyption methods
  28. type TEncryptionMethod = ( eemRijndael,  //0
  29.                            eemTwoFish ); //1
  30.  
  31. //This different hashing methods
  32. type THashingMethod = ( ehmSHA,          //0
  33.                         ehmHaval );      //1
  34.  
  35. type
  36.   TfrmMain = class(TForm)
  37.     Label1                 : TLabel;
  38.     Label2                 : TLabel;
  39.     Label3                 : TLabel;
  40.     Label4                 : TLabel;
  41.     edtPassPhrase: TEdit;
  42.     edtSourceFile          : TEdit;
  43.     edtDestinationFile     : TEdit;
  44.     btBrowseForSource      : TButton;
  45.     btBrowseForDestination : TButton;
  46.     btEncypt               : TButton;
  47.     btDecrypt              : TButton;
  48.     xSaveDialog: TSaveDialog;
  49.     xOpenDialog: TOpenDialog;
  50.     btOptions: TButton;
  51.     txtMessages: TMemo;
  52.     procedure FormCreate(Sender: TObject);
  53.     procedure btBrowseForDestinationClick(Sender: TObject);
  54.     procedure btBrowseForSourceClick(Sender: TObject);
  55.     procedure btDecryptClick(Sender: TObject);
  56.     procedure btEncyptClick(Sender: TObject);
  57.     procedure btOptionsClick(Sender: TObject);
  58.     procedure edtSourceFileExit(Sender: TObject);
  59.   private
  60.       
  61.     //The values chosen by the user in the Option form
  62.     m_eEncryptionMethod : TEncryptionMethod;
  63.     m_eEncryptionMode   : EXEEncryptionMode;
  64.     m_ePaddingMethod    : EXEPaddingMethod;
  65.     m_eHashingMethod    : THashingMethod;
  66.     m_nKeySize          : SmallInt;
  67.  
  68.     function CreateEncryptionMethod( var xEncryptor : TXceedEncryption ) : boolean;
  69.     function DecryptFile( sSourceFilename : string; sDecryptedFilename : string ) : boolean;
  70.     function EncryptFile( sSourceFilename : string; sEncryptedFilename : string ) : boolean;
  71.     function RemoveFileExtension( sFilename : string ) : string;
  72.     procedure SetDestinationFilename();
  73.   public
  74.     { Public declarations }
  75.   end;
  76.  
  77. var
  78.   frmMain: TfrmMain;
  79.  
  80. implementation
  81.  
  82. uses registry, unOptions;
  83.  
  84. {$R *.DFM}
  85.  
  86.  
  87. {***************************************************************}
  88. {                                                               }
  89. { FORM EVENTS                                                   }
  90. {                                                               }
  91. {***************************************************************}
  92.  
  93. {---------------------------------------------------------------}
  94. procedure TfrmMain.FormCreate(Sender: TObject);
  95. var
  96.   xReg : TRegistryIniFile;
  97. begin
  98.   //default value to avoid errors if the options are not set beforehand
  99.   xReg := TRegistryIniFile.Create( 'Software\Xceed\Delphi\Manager' );
  100.   m_eEncryptionMethod := TEncryptionMethod( xReg.ReadInteger( 'Encryption', 'EncryptionMethod', Ord( eemRijndael ) ) );
  101.   m_eEncryptionMode := xReg.ReadInteger( 'Encryption', 'EncryptionMode', emoFreeBlocks );
  102.   m_ePaddingMethod := xReg.ReadInteger( 'Encryption', 'PaddingMethod', epmFIPS81 );
  103.   m_eHashingMethod := THashingMethod( xReg.ReadInteger( 'Encryption', 'HashingMethod', Ord( ehmSHA ) ) );
  104.   m_nKeySize := xReg.ReadInteger( 'Encryption', 'KeySize', 128 );
  105.   xReg.Free();
  106. end;
  107.  
  108. {---------------------------------------------------------------}
  109. { Select the destination folder and the file name that will be  }
  110. { processed when encrypting or decrypting                       }
  111. {---------------------------------------------------------------}
  112. procedure TfrmMain.btBrowseForDestinationClick(Sender: TObject);
  113. begin
  114.   xSaveDialog.Files.Clear();
  115.   xSaveDialog.Title  := 'Destination File';
  116.   xSaveDialog.Filter := 'Encrypted files(*.aes;*.2fs)|*.aes;*.2fs|All files (*.*)|*.*';
  117.   xSaveDialog.FilterIndex := 0;
  118.  
  119.   if( xSaveDialog.Execute ) then
  120.     edtDestinationFile.Text := trim( xSaveDialog.Files.Text )
  121. end;
  122.  
  123. {---------------------------------------------------------------}
  124. { Select the source folder and file name that will be           }
  125. { processed when encrypting or decrypting                       }
  126. {---------------------------------------------------------------}
  127. procedure TfrmMain.btBrowseForSourceClick(Sender: TObject);
  128. begin
  129.   xOpenDialog.Files.Clear();
  130.   xOpenDialog.Title  := 'Source File';
  131.   xOpenDialog.Filter := 'Encrypted files(*.aes;*.2fs)|*.aes;*.2fs|All files (*.*)|*.*';
  132.   xOpenDialog.FilterIndex := 1;
  133.  
  134.   if( xOpenDialog.Execute ) then
  135.   begin
  136.     edtSourceFile.Text := trim( xOpenDialog.Files.Text );
  137.     SetDestinationFilename();
  138.   end;
  139. end;
  140.  
  141. {---------------------------------------------------------------}
  142. { Decrypt the selected source file to the specified destination }
  143. {---------------------------------------------------------------}
  144. procedure TfrmMain.btDecryptClick(Sender: TObject);
  145. begin
  146.   if( DecryptFile( edtSourceFile.Text, edtDestinationFile.Text ) ) then
  147.   begin
  148.     //If the decryption is successful, empty the source and destination
  149.     //edit boxes to simplify subsequent encryption/decryption.
  150.     edtSourceFile.Text := '';
  151.     edtDestinationFile.Text := '';
  152.   end;
  153. end;
  154.  
  155. {---------------------------------------------------------------}
  156. { Encrypt the selected source file to the specified destination }
  157. {---------------------------------------------------------------}
  158. procedure TfrmMain.btEncyptClick(Sender: TObject);
  159. begin
  160.   if( EncryptFile( edtSourceFile.Text, edtDestinationFile.Text ) ) then
  161.   begin
  162.     //If the encryption is successful, emtpy the source and destination
  163.     //edit boxes to simplify subsequent encryption/decryption.
  164.     edtSourceFile.Text := '';
  165.     edtDestinationFile.Text := '';
  166.   end;
  167. end;
  168.  
  169. {---------------------------------------------------------------}
  170. { Display the options form                                      }
  171. {---------------------------------------------------------------}
  172. procedure TfrmMain.btOptionsClick(Sender: TObject);
  173. var
  174.   xOptionsForm : TfrmOptions;
  175.   xReg         : TRegistryIniFile;
  176. begin
  177.   xOptionsForm := TfrmOptions.Create( self );
  178.  
  179.   if xOptionsForm.ShowForm( m_eEncryptionMethod, m_eEncryptionMode,
  180.                             m_ePaddingMethod, m_eHashingMethod, m_nKeySize ) then
  181.   begin
  182.     xReg := TRegistryIniFile.Create( 'Software\Xceed\Delphi\Manager' );
  183.     xReg.WriteInteger( 'Encryption', 'EncryptionMethod', Ord( m_eEncryptionMethod ) );
  184.     xReg.WriteInteger( 'Encryption', 'EncryptionMode', Ord( m_eEncryptionMode ) );
  185.     xReg.WriteInteger( 'Encryption', 'PaddingMethod', Ord( m_ePaddingMethod ) );
  186.     xReg.WriteInteger( 'Encryption', 'HashingMethod', Ord( m_eHashingMethod ) );
  187.     xReg.WriteInteger( 'Encryption', 'KeySize', Ord( m_nKeySize ) );
  188.     xReg.Free();
  189.   end;
  190.  
  191.   xOptionsForm.Destroy();
  192. end;
  193.  
  194. {---------------------------------------------------------------}
  195. { Initialize the destination file to a default value if the     }
  196. { destination text box is empty                                 }
  197. {---------------------------------------------------------------}
  198. procedure TfrmMain.edtSourceFileExit(Sender: TObject);
  199. begin
  200.   SetDestinationFilename();
  201. end;
  202.  
  203. {***************************************************************}
  204. {                                                               }
  205. { FORM FUNCTIONS AND PROCEDURES                                 }
  206. {                                                               }
  207. {***************************************************************}
  208.  
  209. {---------------------------------------------------------------}
  210. { Create an new instance of an encryption method according to   }
  211. { the specified encryption method chosen in the option form.    }
  212. { Set some properties to the encryption method object           }
  213. { appropriate for the selected encryption method and common to  }
  214. { both encryption and decryption since this function will be    }
  215. { called before doing both.                                     }
  216. {---------------------------------------------------------------}
  217. function TfrmMain.CreateEncryptionMethod( var xEncryptor : TXceedEncryption ) : boolean;
  218. var
  219.   xRijndael : DXceedRijndaelEncryptionMethod;
  220.   xTwoFish  : DXceedTwofishEncryptionMethod;
  221.   xHaval    : DXceedHavalHashingMethod;
  222.   xSHA      : DXceedSHAHashingMethod;
  223. begin
  224.   //We instantiate a new encryption method, assigning it directly
  225.   //to the EncryptionMethod property of the XceedEncryption object.
  226.   try
  227.     //Instantiate the right encryption method and set the hashing method
  228.     //that will be used to set the key from the pass phrase.
  229.  
  230.     case m_eEncryptionMethod of
  231.       eemRijndael : begin
  232.                       xRijndael := CoXceedRijndaelEncryptionMethod.Create();
  233.  
  234.                       if( m_eHashingMethod = ehmHaval ) then
  235.                       begin
  236.                         //Haval supports hash sizes equivalent to the supported
  237.                         //key size. So, we can assign the latter to the former
  238.                         //without any problems.
  239.                         xHaval := CoXceedHavalHashingMethod.Create();
  240.                         xHaval.HashSize := m_nKeySize;
  241.                         xRijndael.HashingMethod := xHaval;
  242.                       end;
  243.  
  244.                       if( m_eHashingMethod = ehmSHA ) then
  245.                       begin
  246.                         //We arbitarirly set the HashSize to the maximum key
  247.                         //size allowed so we don't have to worry that the
  248.                         //hash result of the pass phrase could be shorter
  249.                         //than the expected key (although the Xceed Encryption
  250.                         //Library would have dealt with it).
  251.                         xSHA := CoXceedSHAHashingMethod.Create();
  252.                         xSHA.HashSize := 256;
  253.                         xRijndael.HashingMethod := xSHA;
  254.                       end;
  255.                       //Set the secret key of the desired size using the user
  256.                       //pass phrase
  257.                       xRijndael.SetSecretKeyFromPassPhrase( edtPassPhrase.Text, m_nKeySize );
  258.                       //Set the encryption mode
  259.                       xRijndael.EncryptionMode := m_eEncryptionMode;
  260.                       //Set the padding method (for the last encrypted and decrypted block)
  261.                       xRijndael.PaddingMethod := m_ePaddingMethod;
  262.  
  263.                       if( m_eEncryptionMode = emoChainedBlocks ) then
  264.                         //user wants to encrypt in CBC mode. We set the
  265.                         //initialization vector to a random value.
  266.                         xRijndael.SetRandomInitVector();
  267.                         
  268.                       xEncryptor.EncryptionMethod := xRijndael;
  269.                     end;
  270.       eemTwoFish  : begin
  271.                       xTwoFish := CoXceedTwofishEncryptionMethod.Create();
  272.                       if( m_eHashingMethod = ehmHaval ) then
  273.                       begin
  274.                         //Haval supports hash sizes equivalent to the supported
  275.                         //key size. So, we can assign the latter to the former
  276.                         //without any problems.
  277.                         xHaval := CoXceedHavalHashingMethod.Create();
  278.                         xHaval.HashSize := m_nKeySize;
  279.                         xTwoFish.HashingMethod := xHaval;
  280.                       end;
  281.  
  282.                       if( m_eHashingMethod = ehmSHA ) then
  283.                       begin
  284.                         //We arbitarirly set the HashSize to the maximum key
  285.                         //size allowed so we don't have to worry that the
  286.                         //hash result of the pass phrase could be shorter
  287.                         //than the expected key (although the Xceed Encryption
  288.                         //Library would have dealt with it).
  289.                         xSHA := CoXceedSHAHashingMethod.Create();
  290.                         xSHA.HashSize := 256;
  291.                         xTwoFish.HashingMethod := xSHA;
  292.                       end;
  293.                       //Set the secret key of the desired size using the user
  294.                       //pass phrase
  295.                       xTwoFish.SetSecretKeyFromPassPhrase( edtPassPhrase.Text, m_nKeySize );
  296.                       //Set the encryption mode
  297.                       xTwoFish.EncryptionMode := m_eEncryptionMode;
  298.                       //Set the padding method (for the last encrypted and decrypted block)
  299.                       xTwoFish.PaddingMethod := m_ePaddingMethod;
  300.  
  301.                       if( m_eEncryptionMode = emoChainedBlocks ) then
  302.                         //user wants to encrypt in CBC mode. We set the
  303.                         //initialization vector to a random value.
  304.                         xTwoFish.SetRandomInitVector();
  305.  
  306.                       xEncryptor.EncryptionMethod := xTwoFish;
  307.                     end;
  308.     end;
  309.   except
  310.     on xErr : Exception do
  311.     begin
  312.       txtMessages.Text := txtMessages.Text + 'Error initializing the encryption method' + #13#10 +
  313.                           xErr.Message + #13#10;
  314.     end;
  315.   end;
  316.   CreateEncryptionMethod := true;
  317. end;
  318.  
  319. {---------------------------------------------------------------}
  320. { Function that performs the actual decryption of a source file }
  321. { to a destination file.                                        }
  322. {---------------------------------------------------------------}
  323. function TfrmMain.DecryptFile( sSourceFilename : string; sDecryptedFilename : string ) : boolean;
  324. var
  325.   xEncryptor  : TXceedEncryption;
  326.   vaBytesRead : OleVariant;
  327. begin
  328.   Self.Cursor := crHourGlass;
  329.  
  330.   //Create and instance of the XceedEncryption object
  331.   xEncryptor := TXceedEncryption.Create( self );
  332.  
  333.   //Clear the messages list box
  334.   txtMessages.Clear();
  335.  
  336.   //Create and prepare the encryption method
  337.   if( CreateEncryptionMethod( xEncryptor ) ) then
  338.   begin
  339.     try
  340.       //Process the file specifying:
  341.       //  - the source file name
  342.       //  - we want to decrypt the entire file
  343.       //  - decrypt and it's the end of the data
  344.       //  - the destination file name and overwrite it
  345.       //  - the variable that will contain the number of bytes read
  346.       xEncryptor.ProcessFile( sSourceFilename, 0, 0, efpDecrypt, true,
  347.                               sDecryptedFilename, false, vaBytesRead );
  348.  
  349.       //Display a message of success                                                
  350.       txtMessages.Text := txtMessages.Text +
  351.                         sSourceFilename + ' successfully decrypted in ' + sDecryptedFilename + #13#10;
  352.     except
  353.       on xErr : Exception do
  354.         //Display that an error occured
  355.         txtMessages.Text := txtMessages.Text +
  356.                             sSourceFilename + ' failed to decrypt!' + #13#10 +
  357.                             xErr.Message + #13#10;
  358.     end;
  359.   end;
  360.   //Deallocate the Encryption object. The encryption object will free
  361.   //the EncryptionMethod object
  362.   xEncryptor.Free();
  363.   Self.Cursor := crDefault;
  364.   DecryptFile := true;
  365. end;
  366.  
  367. {---------------------------------------------------------------}
  368. { Function that performs the actual encryption of a source file }
  369. { to a destination file.                                        }
  370. {---------------------------------------------------------------}
  371. function TfrmMain.EncryptFile( sSourceFilename : string; sEncryptedFilename : string ) : boolean;
  372. var
  373.   xEncryptor    : TXceedEncryption;  //our XceedEncryption object
  374.   vaBytesRead   : OleVariant;
  375. begin
  376.   Self.Cursor := crHourGlass;
  377.  
  378.   //Create and instance of the XceedEncryption object
  379.   xEncryptor := TXceedEncryption.Create( self );
  380.  
  381.   //Clear the messages list box
  382.   txtMessages.Clear();
  383.  
  384.   //Create and prepare the encryption method
  385.   if( CreateEncryptionMethod( xEncryptor ) ) then
  386.   begin
  387.     try
  388.       //Process the file specifying:
  389.       //  - the source file name
  390.       //  - we want to encrypt the entire file
  391.       //  - encrypt and it's the end of the data
  392.       //  - the destination file name and overwrite it
  393.       //  - the variable that will contain the number of bytes read
  394.  
  395.       xEncryptor.ProcessFile( sSourceFilename, 0, 0, efpEncrypt, true,
  396.                               sEncryptedFilename, false, vaBytesRead );
  397.  
  398.       //Display a message of success                                                
  399.       txtMessages.Text := txtMessages.Text +
  400.                           sSourceFilename + ' successfully encrypted in ' + sEncryptedFilename + #13#10;
  401.     except
  402.       on xErr : Exception do
  403.         //Display that an error occured
  404.         txtMessages.Text := txtMessages.Text +
  405.                             sSourceFilename + ' failed to encrypt!' + #13#10 +
  406.                             xErr.Message + #13#10;
  407.     end;
  408.   end;
  409.   //Deallocate the Encryption object. The encryption object will free
  410.   //the EncryptionMethod object
  411.   xEncryptor.Free();
  412.   Self.Cursor := crDefault;
  413.   EncryptFile := true;
  414. end;
  415.  
  416. {---------------------------------------------------------------}
  417. { Returns the path and filename without it's extension          }
  418. {---------------------------------------------------------------}
  419. function TfrmMain.RemoveFileExtension( sFilename : string ) : string;
  420. var
  421.   i            : integer;
  422.   nFilenameLen : integer;
  423.   nLenToRemove : integer;
  424. begin
  425.   nFilenameLen := Length( sFilename );
  426.   i := nFilenameLen;
  427.   nLenToRemove := -1;
  428.  
  429.   while ( i > 0 ) and ( nLenToRemove = -1 ) do
  430.   begin
  431.     if( copy( sFilename, i, 1 ) = '.' ) then
  432.       nLenToRemove := i - 1;
  433.  
  434.     if( copy( sFilename, i, 1 ) = '\' ) then
  435.       nLenToRemove := nFilenameLen;
  436.  
  437.     i := i - 1;
  438.   end;
  439.  
  440.   if( nLenToRemove = -1 ) then
  441.     RemoveFileExtension := ''
  442.   else
  443.     RemoveFileExtension := copy( sFilename, 0, nLenToRemove );
  444. end;
  445.  
  446. {---------------------------------------------------------------}
  447. { Assign a default value to the destination file name if the    }
  448. { destination text box is empty.                                }
  449. {---------------------------------------------------------------}
  450. procedure TfrmMain.SetDestinationFilename();
  451. var
  452.   sEncryptedFilename : string;
  453. begin
  454.   sEncryptedFilename := edtDestinationFile.Text;
  455.  
  456.   if( length( sEncryptedFilename ) = 0 ) then
  457.   begin
  458.     sEncryptedFilename := RemoveFileExtension( edtSourceFile.Text );
  459.     if( length( sEncryptedFilename ) <> 0 ) then
  460.     begin
  461.       if( m_eEncryptionMethod = eemRijndael ) then
  462.         edtDestinationFile.Text := trim( sEncryptedFilename + '.aes' )
  463.       else
  464.         edtDestinationFile.Text := trim( sEncryptedFilename + '.2fs' );
  465.     end;
  466.   end;
  467.  
  468. end;
  469.  
  470. end.
  471.  
  472.