home *** CD-ROM | disk | FTP | other *** search
/ Chip 2002 September / Chip_2002-09_cd1.bin / zkuste / vbasic / Data / Utils / XZipComp.exe / XceedEncryption.Cab / F113017_MemoryEncryptDlg.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2001-07-04  |  28.3 KB  |  851 lines

  1. // Xceed Encryption Library - Memory Encrypt sample
  2. // Copyright (c) 2001 Xceed Software Inc.
  3. //
  4. // [MemoryEncryptDlg.cpp]
  5. //
  6. // This form module contains the main form's code. It demonstrates how to
  7. // encrypt a chunk of memory data using different kinds of encryption methods,
  8. // and decrypt an Encrypted memory data. It specifically uses:
  9. //  - The SetSecretKeyFromPassPhrase, SetRandomInitVector, 
  10. //    Encrypt and Decrypt methods.
  11. //  - The HashSize, HashingMethod, EncryptionMode, PaddingMethod, 
  12. //    EncryptionMethod, PrivateKey and PublicKey properties.
  13. //
  14. // This file is part of the Xceed Encryption Library sample applications.
  15. // The source code in this file is only intended as a supplement to Xceed
  16. // Encryption Library's documentation, and is provided "as is", without
  17. // warranty of any kind, either expressed or implied.
  18.  
  19.  
  20. #include "stdafx.h"
  21. #include "MemoryEncrypt.h"
  22. #include "MemoryEncryptDlg.h"
  23.  
  24. #include "OptionDlg.h"
  25. #include "KeyPair.h"
  26.  
  27. #ifdef _DEBUG
  28. #define new DEBUG_NEW
  29. #undef THIS_FILE
  30. static char THIS_FILE[] = __FILE__;
  31. #endif
  32.  
  33. /////////////////////////////////////////////////////////////////////////////
  34. // CAboutDlg dialog used for App About
  35.  
  36. class CAboutDlg : public CDialog
  37. {
  38. public:
  39.     CAboutDlg();
  40.  
  41. // Dialog Data
  42.     //{{AFX_DATA(CAboutDlg)
  43.     enum { IDD = IDD_ABOUTBOX };
  44.     //}}AFX_DATA
  45.  
  46.     // ClassWizard generated virtual function overrides
  47.     //{{AFX_VIRTUAL(CAboutDlg)
  48.     protected:
  49.     virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
  50.     //}}AFX_VIRTUAL
  51.  
  52. // Implementation
  53. protected:
  54.     //{{AFX_MSG(CAboutDlg)
  55.     //}}AFX_MSG
  56.     DECLARE_MESSAGE_MAP()
  57. };
  58.  
  59. CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
  60. {
  61.     //{{AFX_DATA_INIT(CAboutDlg)
  62.     //}}AFX_DATA_INIT
  63. }
  64.  
  65. void CAboutDlg::DoDataExchange(CDataExchange* pDX)
  66. {
  67.     CDialog::DoDataExchange(pDX);
  68.     //{{AFX_DATA_MAP(CAboutDlg)
  69.     //}}AFX_DATA_MAP
  70. }
  71.  
  72. BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
  73.     //{{AFX_MSG_MAP(CAboutDlg)
  74.         // No message handlers
  75.     //}}AFX_MSG_MAP
  76. END_MESSAGE_MAP()
  77.  
  78. /////////////////////////////////////////////////////////////////////////////
  79. // CMemoryEncryptDlg dialog
  80.  
  81. CMemoryEncryptDlg::CMemoryEncryptDlg(CWnd* pParent /*=NULL*/)
  82.     : CDialog(CMemoryEncryptDlg::IDD, pParent)
  83. {
  84.     //{{AFX_DATA_INIT(CMemoryEncryptDlg)
  85.     m_sDecryptedText = _T("");
  86.     m_sEncryptedText = _T("");
  87.     m_sPassPhrase = _T("");
  88.     m_nAsymmetricEncryption = -1;
  89.     m_nSymmetricEncryption = -1;
  90.     m_sPrivateKeyFile = _T("");
  91.     m_sPublicKeyFile = _T("");
  92.     //}}AFX_DATA_INIT
  93.     // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
  94.     m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
  95. }
  96.  
  97. void CMemoryEncryptDlg::DoDataExchange(CDataExchange* pDX)
  98. {
  99.     CDialog::DoDataExchange(pDX);
  100.     //{{AFX_DATA_MAP(CMemoryEncryptDlg)
  101.     DDX_Text(pDX, IDC_TXT_DECRYPTEDTEXT, m_sDecryptedText);
  102.     DDX_Text(pDX, IDC_TXT_ENCRYPTEDTEXT, m_sEncryptedText);
  103.     DDX_Text(pDX, IDC_TXT_PASSPHRASE, m_sPassPhrase);
  104.     DDX_Radio(pDX, IDC_RDO_ASYMMETRICENCRYPTION, m_nAsymmetricEncryption);
  105.     DDX_Radio(pDX, IDC_RDO_SYMMETRICENCRYPTION, m_nSymmetricEncryption);
  106.     DDX_Text(pDX, IDC_TXT_PRIVATEKEYFILE, m_sPrivateKeyFile);
  107.     DDX_Text(pDX, IDC_TXT_PUBLICKEYFILE, m_sPublicKeyFile);
  108.     //}}AFX_DATA_MAP
  109. }
  110.  
  111. BEGIN_MESSAGE_MAP(CMemoryEncryptDlg, CDialog)
  112.     //{{AFX_MSG_MAP(CMemoryEncryptDlg)
  113.     ON_WM_SYSCOMMAND()
  114.     ON_WM_PAINT()
  115.     ON_WM_QUERYDRAGICON()
  116.     ON_BN_CLICKED(IDC_CMD_ENCRYPT, OnCmdEncrypt)
  117.     ON_BN_CLICKED(IDQUIT, OnQuit)
  118.     ON_EN_SETFOCUS(IDC_TXT_DECRYPTEDTEXT, OnSetfocusTxtDecryptedtext)
  119.     ON_EN_SETFOCUS(IDC_TXT_ENCRYPTEDTEXT, OnSetfocusTxtEncryptedtext)
  120.     ON_BN_CLICKED(IDC_CMD_DECRYPT, OnCmdDecrypt)
  121.     ON_BN_CLICKED(IDC_CMD_OPTION, OnCmdOption)
  122.     ON_BN_CLICKED(IDC_CMD_RANDOMKEYPAIR, OnCmdRandomkeypair)
  123.     ON_BN_CLICKED(IDC_CMD_SELPRIVATEKEYFILE, OnCmdSelprivatekeyfile)
  124.     ON_BN_CLICKED(IDC_CMD_SELPUBLICKEYFILE, OnCmdSelpublickeyfile)
  125.     ON_BN_CLICKED(IDC_RDO_ASYMMETRICENCRYPTION, OnRdoAsymmetricencryption)
  126.     ON_BN_CLICKED(IDC_RDO_SYMMETRICENCRYPTION, OnRdoSymmetricencryption)
  127.     ON_EN_KILLFOCUS(IDC_TXT_PRIVATEKEYFILE, OnKillfocusTxtPrivatekeyfile)
  128.     ON_EN_KILLFOCUS(IDC_TXT_PUBLICKEYFILE, OnKillfocusTxtPublickeyfile)
  129.     //}}AFX_MSG_MAP
  130. END_MESSAGE_MAP()
  131.  
  132. /////////////////////////////////////////////////////////////////////////////
  133. // CMemoryEncryptDlg message handlers
  134.  
  135. BOOL CMemoryEncryptDlg::OnInitDialog()
  136. {
  137.   //
  138.   // Set default values for the text to Encrypt and the MaxLineLength text box
  139.   //
  140.   m_sDecryptedText = "This is a little test to show you how the memory Encryption works. \r\n"
  141.                      "And it is very easy to use.";
  142.  
  143.   LoadOption();
  144.   EnableControls();
  145.  
  146.     CDialog::OnInitDialog();
  147.  
  148.     // Add "About..." menu item to system menu.
  149.  
  150.     // IDM_ABOUTBOX must be in the system command range.
  151.     ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
  152.     ASSERT(IDM_ABOUTBOX < 0xF000);
  153.  
  154.     CMenu* pSysMenu = GetSystemMenu(FALSE);
  155.     if (pSysMenu != NULL)
  156.     {
  157.         CString strAboutMenu;
  158.         strAboutMenu.LoadString(IDS_ABOUTBOX);
  159.         if (!strAboutMenu.IsEmpty())
  160.         {
  161.             pSysMenu->AppendMenu(MF_SEPARATOR);
  162.             pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
  163.         }
  164.     }
  165.  
  166.     // Set the icon for this dialog.  The framework does this automatically
  167.     //  when the application's main window is not a dialog
  168.     SetIcon(m_hIcon, TRUE);            // Set big icon
  169.     SetIcon(m_hIcon, FALSE);        // Set small icon
  170.  
  171.     return TRUE;  // return TRUE  unless you set the focus to a control
  172. }
  173.  
  174. void CMemoryEncryptDlg::OnSysCommand(UINT nID, LPARAM lParam)
  175. {
  176.     if ((nID & 0xFFF0) == IDM_ABOUTBOX)
  177.     {
  178.         CAboutDlg dlgAbout;
  179.         dlgAbout.DoModal();
  180.     }
  181.     else
  182.     {
  183.         CDialog::OnSysCommand(nID, lParam);
  184.     }
  185. }
  186.  
  187. // If you add a minimize button to your dialog, you will need the code below
  188. //  to draw the icon.  For MFC applications using the document/view model,
  189. //  this is automatically done for you by the framework.
  190.  
  191. void CMemoryEncryptDlg::OnPaint() 
  192. {
  193.     if (IsIconic())
  194.     {
  195.         CPaintDC dc(this); // device context for painting
  196.  
  197.         SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
  198.  
  199.         // Center icon in client rectangle
  200.         int cxIcon = GetSystemMetrics(SM_CXICON);
  201.         int cyIcon = GetSystemMetrics(SM_CYICON);
  202.         CRect rect;
  203.         GetClientRect(&rect);
  204.         int x = (rect.Width() - cxIcon + 1) / 2;
  205.         int y = (rect.Height() - cyIcon + 1) / 2;
  206.  
  207.         // Draw the icon
  208.         dc.DrawIcon(x, y, m_hIcon);
  209.     }
  210.     else
  211.     {
  212.         CDialog::OnPaint();
  213.     }
  214. }
  215.  
  216. // The system calls this to obtain the cursor to display while the user drags
  217. //  the minimized window.
  218. HCURSOR CMemoryEncryptDlg::OnQueryDragIcon()
  219. {
  220.     return (HCURSOR) m_hIcon;
  221. }
  222.  
  223. //====================================================================================
  224. //
  225. // EVENTS - triggered by the form and its controls
  226. //
  227. //====================================================================================
  228.  
  229. void CMemoryEncryptDlg::OnSetfocusTxtDecryptedtext() 
  230. {
  231.   SetDefID( IDC_CMD_ENCRYPT );
  232. }
  233.  
  234. void CMemoryEncryptDlg::OnSetfocusTxtEncryptedtext() 
  235. {
  236.   SetDefID( IDC_CMD_DECRYPT );
  237. }
  238.  
  239. //------------------------------------------------------------------------------------
  240. // Quit the sample application
  241. //------------------------------------------------------------------------------------
  242. void CMemoryEncryptDlg::OnQuit() 
  243. {
  244.   EndDialog( IDOK );
  245. }
  246.  
  247. //------------------------------------------------------------------------------------
  248. // Do the Encryption of the Decrypted text
  249. //------------------------------------------------------------------------------------
  250. void CMemoryEncryptDlg::OnCmdEncrypt() 
  251. {
  252.   if( UpdateData( TRUE ) )
  253.   {
  254.     CWaitCursor xWaitCursor;
  255.  
  256.     COleException* pExcept = new COleException;
  257.     DXceedEncryption xEncryptor;
  258.     COleVariant vaEncrypted;
  259.     COleVariant vaToEncrypt;
  260.  
  261.     try
  262.     {
  263.       // Create an instance of the XceedEncryption class
  264.       if( !xEncryptor.CreateDispatch( "Xceed.Encryption", pExcept ) )
  265.       {
  266.         throw pExcept;
  267.       }
  268.  
  269.       // Create and prepare the Encryption Method
  270.       // This function can throw an exception that will be caught here.
  271.       PrepareEncryptionMethod( xEncryptor );
  272.  
  273.       // Store in the variant to Encrypt the content of the text box 
  274.       // as an ANSI String. We could have used a BSTR representation
  275.       // of the string but it would have unnecessarily double the string size.
  276.       // The Variant will report containing a VT_BSTR, but the actual data and 
  277.       // size will reflect the Ansi string format.
  278.       vaToEncrypt.SetString( m_sDecryptedText, VT_BSTRT );
  279.  
  280.       // Encrypt the string in a single call (bEndOfData is TRUE)
  281.       vaEncrypted = xEncryptor.Encrypt( &vaToEncrypt, TRUE );
  282.  
  283.       // We assign an empty string as a default Encrypted value.
  284.       m_sEncryptedText = "";
  285.  
  286.       // We check that the Encrypted variant is really a byte array. For instance,
  287.       // it won't be if there was no characters to Encrypt (empty string).
  288.       if( vaEncrypted.vt == ( VT_ARRAY | VT_UI1 ) )
  289.       {
  290.         // Encode the encrypted variant in hexadecimal representation.
  291.         m_sEncryptedText = BinaryToHex( &vaEncrypted );
  292.       }
  293.  
  294.       // Update mainly the Encrypted text box
  295.       UpdateData( FALSE );
  296.     }
  297.     catch( COleDispatchException* pEx )
  298.     {
  299.       pEx->ReportError();
  300.       pEx->Delete();
  301.     }
  302.     catch( COleException* pEx )
  303.     {
  304.       pEx->ReportError();
  305.       pEx->Delete();
  306.     }
  307.     catch( CException* pEx )
  308.     {
  309.       pEx->ReportError();
  310.       pEx->Delete();
  311.     }
  312.  
  313.     pExcept->Delete();
  314.   }
  315. }
  316.  
  317. //------------------------------------------------------------------------------------
  318. // Do the Decryption of the Encrypted text
  319. //------------------------------------------------------------------------------------
  320. void CMemoryEncryptDlg::OnCmdDecrypt() 
  321. {
  322.   if( UpdateData( TRUE ) )
  323.   {
  324.     CWaitCursor xWaitCursor;
  325.  
  326.     COleException* pEx = new COleException;
  327.     DXceedEncryption xEncryptor;
  328.     COleVariant vaEncrypted;
  329.     COleVariant vaDecrypted;
  330.  
  331.     try
  332.     {
  333.       // Create an instance of the XceedEncryption class
  334.       if( !xEncryptor.CreateDispatch( "Xceed.Encryption", pEx ) )
  335.       {
  336.         throw pEx;
  337.       }
  338.  
  339.       // Create and prepare the Encryption Method
  340.       // This function can throw an exception that will be caught here.
  341.       PrepareEncryptionMethod( xEncryptor );
  342.  
  343.       // Store in the variant to Decrypt the content of the decrypted text box, 
  344.       // which is in hexadecimal representation, converted to binary form.
  345.       vaEncrypted = HexToBinary( m_sEncryptedText );
  346.  
  347.       // Decrypt the string in a single call (bEndOfData is TRUE).
  348.       vaDecrypted = xEncryptor.Decrypt( vaEncrypted, TRUE );
  349.  
  350.       // We assign an empty string as a default Decrypted value.
  351.       m_sDecryptedText = "";
  352.  
  353.       // We check that the Decrypted variant is really a byte array. For instance,
  354.       // it won't be if there was no characters to Decrypt (empty string).
  355.       if( vaDecrypted.vt == ( VT_ARRAY | VT_UI1 ) )
  356.       {
  357.         LONG lHigh;
  358.         LONG lLow;
  359.  
  360.         // We extracts the upper bound and the lower bound of the
  361.         // byte array.
  362.         SafeArrayGetUBound( vaDecrypted.parray, 1, &lHigh );
  363.         SafeArrayGetLBound( vaDecrypted.parray, 1, &lLow );
  364.  
  365.         // This pointer will contain the address of the byte array
  366.         char* pszDecrypted = NULL;
  367.  
  368.         // We get a pointer on the actual data in the safe array.
  369.         SafeArrayAccessData( vaDecrypted.parray, (void**)&pszDecrypted );
  370.  
  371.         // We display the Decrypted string by assigning this Ansi string
  372.         // to the CString member, using the constructor accepting a char* and a size.
  373.         m_sDecryptedText = CString( pszDecrypted, lHigh - lLow + 1 );
  374.  
  375.         // We release the lock on the safe array
  376.         SafeArrayUnaccessData( vaDecrypted.parray );
  377.       }
  378.  
  379.       // Update mainly the Decrypted text box
  380.       UpdateData( FALSE );
  381.     }
  382.     catch( COleDispatchException* pExcept )
  383.     {
  384.       pExcept->ReportError();
  385.       pExcept->Delete();
  386.     }
  387.     catch( COleException* pExcept )
  388.     {
  389.       pExcept->ReportError();
  390.       pExcept->Delete();
  391.     }
  392.     catch( CException* pExcept )
  393.     {
  394.       pExcept->ReportError();
  395.       pExcept->Delete();
  396.     }
  397.  
  398.     pEx->Delete();
  399.   }
  400. }
  401.  
  402. //------------------------------------------------------------------------------------
  403. // Display the options form, saving them if the user click OK
  404. //------------------------------------------------------------------------------------
  405. void CMemoryEncryptDlg::OnCmdOption() 
  406. {
  407.     COptionDlg dlgOption;
  408.  
  409.   if( dlgOption.ShowForm( &m_eEncryptionMethod, &m_eEncryptionMode, &m_eHashingMethod,
  410.                           &m_nSecretKeySize, &m_ePaddingMethod ) )
  411.   {
  412.     SaveOption();
  413.   }
  414. }
  415.  
  416. //------------------------------------------------------------------------------------
  417. // Generate new private and public keys stored in the file specified in the
  418. // respective text boxes.
  419. //------------------------------------------------------------------------------------
  420. void CMemoryEncryptDlg::OnCmdRandomkeypair() 
  421. {
  422.     CKeyPair dlgKeyPair;
  423.  
  424.   if( UpdateData( TRUE ) )
  425.   {
  426.     if( m_sPrivateKeyFile.IsEmpty() || m_sPublicKeyFile.IsEmpty() )
  427.     {
  428.       AfxMessageBox( "You must specify the key file names where will be stored the private and public keys" );
  429.     }
  430.     else
  431.     {
  432.       dlgKeyPair.ShowForm( m_sPrivateKeyFile, m_sPublicKeyFile );
  433.     }
  434.   }
  435. }
  436.  
  437. //------------------------------------------------------------------------------------
  438. // Select the file name that contain (or will contain) the private key.
  439. //------------------------------------------------------------------------------------
  440. void CMemoryEncryptDlg::OnCmdSelprivatekeyfile() 
  441. {
  442.   CString sKeyFile;
  443.  
  444.   sKeyFile = SelectKeyFile();
  445.   if( !sKeyFile.IsEmpty() )
  446.   {
  447.     m_sPrivateKeyFile = sKeyFile;
  448.     UpdateData( FALSE );
  449.     SavePrivateKeyFileSetting();
  450.   }
  451. }
  452.  
  453. //------------------------------------------------------------------------------------
  454. // Select the file name that contain (or will contain) the public key.
  455. //------------------------------------------------------------------------------------
  456. void CMemoryEncryptDlg::OnCmdSelpublickeyfile() 
  457. {
  458.   CString sKeyFile;
  459.  
  460.   sKeyFile = SelectKeyFile();
  461.   if( !sKeyFile.IsEmpty() )
  462.   {
  463.     m_sPublicKeyFile = sKeyFile;
  464.     UpdateData( FALSE );
  465.     SavePublicKeyFileSetting();
  466.   }
  467. }
  468.  
  469. void CMemoryEncryptDlg::OnKillfocusTxtPrivatekeyfile() 
  470. {
  471.   SavePrivateKeyFileSetting();
  472. }
  473.  
  474. void CMemoryEncryptDlg::OnKillfocusTxtPublickeyfile() 
  475. {
  476.   SavePublicKeyFileSetting();
  477. }
  478.  
  479. //------------------------------------------------------------------------------------
  480. // The user selected asymmetric mode, disable controls associated with symmetric
  481. // encryption
  482. //------------------------------------------------------------------------------------
  483. void CMemoryEncryptDlg::OnRdoAsymmetricencryption() 
  484. {
  485.   if( UpdateData( TRUE ) )
  486.   {
  487.     m_nSymmetricEncryption = -1;
  488.  
  489.     UpdateData( FALSE );
  490.  
  491.     EnableControls();
  492.     SaveEncryptionType();
  493.   }
  494. }
  495.  
  496. //------------------------------------------------------------------------------------
  497. // The user selected symmetric mode, disable controls associated with asymmetric
  498. // encryption
  499. //------------------------------------------------------------------------------------
  500. void CMemoryEncryptDlg::OnRdoSymmetricencryption() 
  501. {
  502.   if( UpdateData( TRUE ) )
  503.   {
  504.     m_nAsymmetricEncryption = -1;
  505.  
  506.     UpdateData( FALSE );
  507.  
  508.     EnableControls();
  509.     SaveEncryptionType();
  510.   }
  511. }
  512.  
  513. //====================================================================================
  514. //
  515. // FUNCTIONS
  516. //
  517. //====================================================================================
  518.  
  519. //------------------------------------------------------------------------------------
  520. // Enable the control associated with the selected encryption type (symmetric or
  521. // asymmetric). Disable the other controls.
  522. //------------------------------------------------------------------------------------
  523. void CMemoryEncryptDlg::EnableControls()
  524. {
  525.   BOOL bSecretKeyEncryption = ( m_nSymmetricEncryption > -1 );
  526.  
  527.   GetDlgItem( IDC_TXT_PASSPHRASE )->EnableWindow( bSecretKeyEncryption );
  528.   GetDlgItem( IDC_CMD_OPTION )->EnableWindow( bSecretKeyEncryption );
  529.  
  530.   GetDlgItem( IDC_TXT_PRIVATEKEYFILE )->EnableWindow( !bSecretKeyEncryption );
  531.   GetDlgItem( IDC_CMD_SELPRIVATEKEYFILE )->EnableWindow( !bSecretKeyEncryption );
  532.   GetDlgItem( IDC_TXT_PUBLICKEYFILE )->EnableWindow( !bSecretKeyEncryption );
  533.   GetDlgItem( IDC_CMD_SELPUBLICKEYFILE )->EnableWindow( !bSecretKeyEncryption );
  534.   GetDlgItem( IDC_CMD_RANDOMKEYPAIR )->EnableWindow( !bSecretKeyEncryption );
  535. }
  536.  
  537. //------------------------------------------------------------------------------------
  538. // Load in the member variables the options saved in the registry the last
  539. // time this sample file manager was called.
  540. //------------------------------------------------------------------------------------
  541. void CMemoryEncryptDlg::LoadOption()
  542. {
  543.   m_eEncryptionMethod = ( enuEncryptionMethod )AfxGetApp()->GetProfileInt( "Encryption", "EncryptionMethod", eemRijndael );
  544.   m_eEncryptionMode = ( enuEncryptionMode )AfxGetApp()->GetProfileInt( "Encryption", "EncryptionMode", emoFreeBlocks );
  545.   m_ePaddingMethod = ( enuPaddingMethod )AfxGetApp()->GetProfileInt( "Encryption", "PaddingMethod", epmFIPS81 );
  546.   m_eHashingMethod = ( enuHashingMethod )AfxGetApp()->GetProfileInt( "Encryption", "HashingMethod", ehmHaval );
  547.   m_nSecretKeySize = AfxGetApp()->GetProfileInt( "Encryption", "SecretKeySize", 128 );
  548.   m_sPrivateKeyFile = AfxGetApp()->GetProfileString( "Encryption", "PrivateKeyFile", "");
  549.   m_sPublicKeyFile = AfxGetApp()->GetProfileString( "Encryption", "PublicKeyFile", "");
  550.   m_nAsymmetricEncryption = AfxGetApp()->GetProfileInt( "Encryption", "Asymmetric", -1 );
  551.   m_nSymmetricEncryption = AfxGetApp()->GetProfileInt( "Encryption", "Symmetric", 0 );
  552.  
  553.   UpdateData( FALSE );
  554. }
  555.  
  556. //------------------------------------------------------------------------------------
  557. // Prepare the Encryption Method according to the user selection
  558. //------------------------------------------------------------------------------------
  559. void CMemoryEncryptDlg::PrepareEncryptionMethod( DXceedEncryption& xEncryptor )
  560. {
  561.   if( UpdateData( TRUE ) )
  562.   {
  563.     COleException* pEx = new COleException;
  564.  
  565.     if( m_nSymmetricEncryption > -1 )
  566.     {
  567.       // The user chose to perform symmetric encryption/decryption
  568.  
  569.       switch( m_eEncryptionMethod )
  570.       {
  571.         //
  572.         // The user chose RIJNDAEL
  573.         //
  574.         case eemRijndael :
  575.         {
  576.           // Instanciate the Rijndael encryption method
  577.           DXceedRijndaelEncryptionMethod xRijndael;
  578.  
  579.           if( !xRijndael.CreateDispatch( "Xceed.RijndaelEncryptionMethod", pEx ) )
  580.           {
  581.             throw pEx;
  582.           }
  583.  
  584.           // Set the hashing method that will be used to set the key from
  585.           // the pass phrase.
  586.           switch( m_eHashingMethod )
  587.           {
  588.             case ehmHaval :
  589.             {
  590.               DXceedHavalHashingMethod xHaval;
  591.               if( !xHaval.CreateDispatch( "Xceed.HavalHashingMethod", pEx ) )
  592.               {
  593.                 throw pEx;
  594.               }
  595.               // Haval supports hash sizes equivalent to the supported
  596.               // key size. So, we can assign the latter to the
  597.               // former without problem.
  598.               xHaval.SetHashSize( m_nSecretKeySize );
  599.               xRijndael.SetRefHashingMethod( xHaval.m_lpDispatch );
  600.             }
  601.             break;
  602.  
  603.             case ehmSHA :
  604.             {
  605.               DXceedSHAHashingMethod xSHA;
  606.               if( !xSHA.CreateDispatch( "Xceed.SHAHashingMethod", pEx ) )
  607.               {
  608.                 throw pEx;
  609.               }
  610.               // We arbitrarily set the HashSize to the maximum key
  611.               // size allowed so we don't have to worry that the hash
  612.               // result of the pass phrase could be shorter than the
  613.               // expected key (although the Xceed Encryption Library
  614.               // would have deal with it).
  615.               xSHA.SetHashSize( 256 );
  616.               xRijndael.SetRefHashingMethod( xSHA.m_lpDispatch );
  617.             }
  618.             break;
  619.           }
  620.  
  621.           // Set the secret key of the desired size using the user pass phrase
  622.           xRijndael.SetSecretKeyFromPassPhrase( m_sPassPhrase, m_nSecretKeySize );
  623.  
  624.           // Set the encryption mode
  625.           xRijndael.SetEncryptionMode( m_eEncryptionMode );
  626.  
  627.           // Set the padding method (for the last encrypted or decrypted
  628.           // block)
  629.           xRijndael.SetPaddingMethod( m_ePaddingMethod );
  630.  
  631.           if( m_eEncryptionMode == emoChainedBlocks )
  632.           {
  633.             // Will be useful only when encrypting since, in decryption,
  634.             // the InitVector is read at the beginning of the encrypted text.
  635.             xRijndael.SetRandomInitVector();
  636.           }
  637.  
  638.           // Set the previously initialized Encryption Method of the Encryptor object
  639.           // received as a parameter of this function.
  640.           xEncryptor.SetRefEncryptionMethod( xRijndael.m_lpDispatch );
  641.  
  642.           // Free the temporary Encryption Method. The previous assignation adding
  643.           // a reference to the Encryption Method object, this object will effectively
  644.           // be freed by the xEncryptr object when the latter will be released.
  645.           break;
  646.         }
  647.  
  648.         //
  649.         // The user chose TWOFISH
  650.         //
  651.         case eemTwofish :
  652.         {
  653.           // Instanciate the Twofish encryption method
  654.           DXceedTwofishEncryptionMethod xTwofish;
  655.  
  656.           if( !xTwofish.CreateDispatch( "Xceed.TwofishEncryptionMethod", pEx ) )
  657.           {
  658.             throw pEx;
  659.           }
  660.  
  661.           // Set the hashing method that will be used to set the key from
  662.           // the pass phrase.
  663.           switch( m_eHashingMethod )
  664.           {
  665.             case ehmHaval :
  666.             {
  667.               DXceedHavalHashingMethod xHaval;
  668.               if( !xHaval.CreateDispatch( "Xceed.HavalHashingMethod", pEx ) )
  669.               {
  670.                 throw pEx;
  671.               }
  672.               // Haval supports hash sizes equivalent to the supported
  673.               // key size. So, we can assign the latter to the
  674.               // former without problem.
  675.               xHaval.SetHashSize( m_nSecretKeySize );
  676.               xTwofish.SetRefHashingMethod( xHaval.m_lpDispatch );
  677.             }
  678.  
  679.             case ehmSHA :
  680.             {
  681.               DXceedSHAHashingMethod xSHA;
  682.               if( !xSHA.CreateDispatch( "Xceed.SHAHashingMethod", pEx ) )
  683.               {
  684.                 throw pEx;
  685.               }
  686.               // We arbitrarily set the HashSize to the maximum key
  687.               // size allowed so we don't have to worry that the hash
  688.               // result of the pass phrase could be shorter than the
  689.               // expected key (although the Xceed Encryption Library
  690.               // would have deal with it).
  691.               xSHA.SetHashSize( 256 );
  692.               xTwofish.SetRefHashingMethod( xSHA.m_lpDispatch );
  693.             }
  694.           }
  695.  
  696.           // Set the secret key of the desired size using the user pass phrase
  697.           xTwofish.SetSecretKeyFromPassPhrase( m_sPassPhrase, m_nSecretKeySize );
  698.  
  699.           // Set the encryption mode
  700.           xTwofish.SetEncryptionMode( m_eEncryptionMode );
  701.  
  702.           // Set the padding method (for the last encrypted or decrypted
  703.           // block)
  704.           xTwofish.SetPaddingMethod( m_ePaddingMethod );
  705.  
  706.           if( m_eEncryptionMode == emoChainedBlocks )
  707.           {
  708.             // Will be useful only when encrypting since, in decryption,
  709.             // the InitVector is read at the beginning of the encrypted text.
  710.             xTwofish.SetRandomInitVector();
  711.           }
  712.  
  713.           // Set the previously initialized Encryption Method of the Encryptor object
  714.           // received as a parameter of this function.
  715.           xEncryptor.SetRefEncryptionMethod( xTwofish.m_lpDispatch );
  716.  
  717.           // Free the temporary Encryption Method. The previous assignation adding
  718.           // a reference to the Encryption Method object, this object will effectively
  719.           // be freed by the xEncryptor object when the latter will be released.
  720.           break;
  721.         }
  722.       }
  723.     }
  724.     else
  725.     {
  726.       // The user chose to perform asymmetric encryption/decryption
  727.       
  728.       if( m_nAsymmetricEncryption > -1 )
  729.       {
  730.         // Instanciate the RSA encryption method
  731.         DXceedRSAEncryptionMethod xRSA;
  732.  
  733.         if( !xRSA.CreateDispatch( "Xceed.RSAEncryptionMethod", pEx ) )
  734.         {
  735.           throw pEx;
  736.         }
  737.  
  738.         COleVariant vaPrivateKey;
  739.         COleVariant vaPublicKey;
  740.  
  741.         // Initialize the private key (used when decrypting)
  742.         ReadKeyFile( m_sPrivateKeyFile, &xEncryptor, &vaPrivateKey );
  743.         xRSA.SetPrivateKey( &vaPrivateKey );
  744.  
  745.         // Initialize the public key (used when encrypting)
  746.         ReadKeyFile( m_sPublicKeyFile, &xEncryptor, &vaPublicKey );
  747.         xRSA.SetPublicKey( &vaPublicKey );
  748.  
  749.         xEncryptor.SetRefEncryptionMethod( xRSA.m_lpDispatch );
  750.       }
  751.     }
  752.  
  753.     pEx->Delete();
  754.   }
  755. }
  756.  
  757. //------------------------------------------------------------------------------------
  758. // Read the content of the specified file, allegedly containing a private or public
  759. // key in hexadecimal representation.
  760. // Return the key in the pvaKey parameter. This function can return Empty.
  761. //------------------------------------------------------------------------------------
  762. void CMemoryEncryptDlg::ReadKeyFile( LPCSTR sKeyFileName, 
  763.                                      DXceedEncryption* pxEncryptor, 
  764.                                      COleVariant* pvaKey )
  765. {
  766.   pvaKey->Clear();
  767.  
  768.   CStdioFile xKeyFile;
  769.  
  770.   if( xKeyFile.Open( sKeyFileName, CFile::modeRead ) )
  771.   {
  772.     CString sBuffer;
  773.     CString sTemp;
  774.  
  775.     sBuffer = "";
  776.     while( xKeyFile.ReadString( sTemp ) )
  777.     {
  778.       sTemp.TrimRight();
  779.       sBuffer += sTemp;
  780.     }
  781.  
  782.     if( !sBuffer.IsEmpty() )
  783.     {
  784.       *pvaKey = HexToBinary( sBuffer );
  785.     }
  786.   }
  787.   else
  788.   {
  789.     AfxMessageBox( "Error opening key file" );
  790.   }
  791. }
  792.  
  793. //------------------------------------------------------------------------------------
  794. // Save the current options from the member variables in the registry
  795. //------------------------------------------------------------------------------------
  796. void CMemoryEncryptDlg::SaveOption()
  797. {
  798.   AfxGetApp()->WriteProfileInt( "Encryption", "EncryptionMethod", m_eEncryptionMethod );
  799.   AfxGetApp()->WriteProfileInt( "Encryption", "EncryptionMode", m_eEncryptionMode );
  800.   AfxGetApp()->WriteProfileInt( "Encryption", "PaddingMethod", m_ePaddingMethod );
  801.   AfxGetApp()->WriteProfileInt( "Encryption", "HashingMethod", m_eHashingMethod );
  802.   AfxGetApp()->WriteProfileInt( "Encryption", "SecretKeySize", m_nSecretKeySize );
  803. }
  804.  
  805. //------------------------------------------------------------------------------------
  806. // Save the current selected (and deselected) encryption type (symmetric or asymmetric)
  807. //------------------------------------------------------------------------------------
  808. void CMemoryEncryptDlg::SaveEncryptionType()
  809. {
  810.   if( UpdateData( TRUE ) )
  811.   {
  812.     AfxGetApp()->WriteProfileInt( "Encryption", "Asymmetric", m_nAsymmetricEncryption );
  813.     AfxGetApp()->WriteProfileInt( "Encryption", "Symmetric", m_nSymmetricEncryption );
  814.   }
  815. }
  816.  
  817. //------------------------------------------------------------------------------------
  818. // Save the current private key file name
  819. //------------------------------------------------------------------------------------
  820. void CMemoryEncryptDlg::SavePrivateKeyFileSetting()
  821. {
  822.   if( UpdateData( TRUE ) )
  823.   {
  824.     AfxGetApp()->WriteProfileString( "Encryption", "PrivateKeyFile", m_sPrivateKeyFile );
  825.   }
  826. }
  827.  
  828. //------------------------------------------------------------------------------------
  829. // Save the current public key file name
  830. //------------------------------------------------------------------------------------
  831. void CMemoryEncryptDlg::SavePublicKeyFileSetting()
  832. {
  833.   if( UpdateData( TRUE ) )
  834.   {
  835.     AfxGetApp()->WriteProfileString( "Encryption", "PublicKeyFile", m_sPublicKeyFile );
  836.   }
  837. }
  838.  
  839. CString CMemoryEncryptDlg::SelectKeyFile()
  840. {
  841.   CString szFileSelected;
  842.   CFileDialog dlgOpen( TRUE, "key", NULL, 0, "Key file (*.key)|*.key|All type (*.*)|*.*||", this );
  843.  
  844.   if( dlgOpen.DoModal() == IDOK )
  845.   {
  846.     szFileSelected = dlgOpen.GetPathName();
  847.   }
  848.  
  849.   return szFileSelected;
  850. }
  851.