home *** CD-ROM | disk | FTP | other *** search
- /* Xceed Encryption Library - Encrypt Sample Application
- * Copyright (c) 2001 Xceed Software Inc.
- *
- * [Encrypt.cpp]
- *
- * This console application shows how to encrypt a file, using different
- * encryption methods. It specifically demonstrates:
- * - The SetSecretKeyFromPassPhrase, SetRandomInitVector, WriteFile and
- * ProcessFile methods.
- * - The EncryptionMethod, EncryptionMode properties.
- *
- * This file is part of the Xceed Encryption Library sample
- * applications. The source code in this file is only intended as
- * a supplement to Xceed Encryption Library's documentation,
- * and is provided "as is", without warranty of any kind, either
- * expressed or implied.
- */
-
- #include "stdafx.h"
- #include <stdio.h>
- #include <string.h>
- #include <limits.h>
- #include "Encrypt.h"
-
- //
- // Mapping between command-line and property values
- //
- // The RSA Decryption method is not supported in this sample as it will rarely be used
- // to encrypt/decrypt a file. RSA is not efficient to encrypt large chunks of data.
-
- static SEncryptionMethod g_pxEncryptionMethods[] =
- {
- { "=AES", emRijndael },
- { "=Twofish", emTwofish }
- };
-
-
- //
- // Entry point of the application
- //
-
- int main(int argc, char* argv[])
- {
- CoInitialize( NULL );
-
- try
- {
- // Create an instance of the XceedEncryption coclass, and
- // use the "I" interface which manipulates byte arrays instead of
- // Variants as the "D" interface does.
- IXceedEncryptionPtr piEncrypt;
- piEncrypt.CreateInstance( CLSID_XceedEncryption );
-
- // Two BSTR variables that will contain the Input and Output file names.
- _bstr_t bstrInputFileName;
- _bstr_t bstrOutputFileName;
-
- // Extract the command line parameters and initialize the Encryption
- // instance according to the user specification. After this call
- // the Encryption instance piEncrypt is ready to encrypt.
- if( !ExtractParameters( argc, argv,
- piEncrypt,
- bstrInputFileName,
- bstrOutputFileName ) )
- {
- // There's been an error extracting the command-line parameters or the
- // user requested some help.
- ShowHelp();
- return 1;
- }
-
- if( bstrInputFileName.length() == 0 )
- {
- // An input file name was not provided by the user.
- // Get the source from the console
-
- printf( "Encrypting the console input. Press Ctrl-Z and Enter when done.\n\n" );
-
- // We call WriteFile first, passing a null buffer to encrypt.
- // Useful to overwrite the destination file (bAppend set to FALSE).
- DWORD dwBytesWritten = 0;
- piEncrypt->WriteFile( NULL, 0, efpEncrypt, FALSE, bstrOutputFileName, FALSE, &dwBytesWritten );
-
- char pcBuffer[ BUFFER_SIZE ];
-
- while( !feof( stdin ) )
- {
- // Read from the console BUFFER_SIZE characters at a time.
- int nRead = fread( pcBuffer, sizeof( char ), BUFFER_SIZE, stdin );
-
- if( nRead )
- {
- // Encrypt by reading a buffer and sending the output to a file.
- // We specify :
- // - The source buffer, with the size, since we want
- // to encrypt all the source buffer.
- // - The processing we want to perform, in this case efpEncrypt.
- // - The bEndOfData parameter set to FALSE, since we do the
- // processing in multiple block.
- // - The destination filename, with the bAppend parameter set to FALSE
- // since we want to overwrite any existing file.
- // - The address of two DWORD that will receive the number of bytes
- // actually read from the source, and written to the destination.
- piEncrypt->WriteFile( ( BYTE* )pcBuffer, nRead, efpEncrypt, FALSE, bstrOutputFileName, TRUE, &dwBytesWritten );
- }
- }
-
- // Since we always called with bEndOfData to FALSE, we must
- // make sure to flush the remaining data.
- piEncrypt->WriteFile( NULL, 0, efpEncrypt, TRUE, bstrOutputFileName, TRUE, &dwBytesWritten );
-
- printf( "Successfully encrypted the console input to file %s\n", ( const char* )bstrOutputFileName );
- }
- else
- {
- // An input file name was provided by the user.
- // Read the input file and output the result to the specified file
-
- DWORD dwBytesRead = 0;
- DWORD dwBytesWritten = 0;
-
- // Encrypt by reading a file and sending the output to another file.
- // We specify :
- // - The source filename, without any offset or size, since we want
- // to encrypt all the source file.
- // - The processing we want to perform, in this case efpEncrypt.
- // - The bEndOfData parameter set to TRUE, since we do all the
- // processing in a single block.
- // - The destination filename, with the bAppend parameter set to FALSE
- // since we want to overwrite any existing file.
- // - The address of two DWORD that will receive the number of bytes
- // actually read from the source, and written to the destination.
- piEncrypt->ProcessFile( bstrInputFileName, 0, 0, efpEncrypt, TRUE,
- bstrOutputFileName, FALSE,
- &dwBytesRead, &dwBytesWritten );
-
- // Write the encryption statistics to the screen.
- printf( "Successfully encrypted file %s [%d] to file %s [%d]\n",
- ( const char* )bstrInputFileName, dwBytesRead,
- ( const char* )bstrOutputFileName, dwBytesWritten );
- }
- }
- catch( const _com_error& err )
- {
- // When using the "#import" directive, the compiler generates wrapper classes
- // around all interface types. These wrapper classes throw exceptions when
- // a method call returns an HRESULT which is a failure code.
- printf( "Error %08x: %s\n", err.Error(), ( const char* )err.Description() );
- }
- catch( ... )
- {
- // Catch any other exceptions
- printf( "An unknown error occured.\n" );
- }
-
- // Close the COM library for the current thread
- CoUninitialize();
-
- return 0;
- }
-
- //--------------------------------------------------------------------------
- // Display usage information
- //--------------------------------------------------------------------------
- void ShowHelp()
- {
- // "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
- printf( "Usage: Encrypt [options] [input_file] pass_phrase output_file\n\n"
- " input_file: the file to encrypt\n"
- " pass_phrase: the passphrase used to produce the secret key (between \"\" if\n"
- " you use spaces.\n"
- " output_file: the destination file\n\n"
- " options: /m=[AES | Twofish]\n"
- " This is the encryption method. The default is 'AES' (Rijndael)\n"
- " /h or /? : Show this help\n" );
- }
-
- //--------------------------------------------------------------------------
- // Extract commands from the parameters
- //
- // In this function, we call the piEncrypt interface and let exceptions
- // be caught by the caller.
- // This function returns false if an error occured parsing the command
- // line parameters or if the user requested help.
- //--------------------------------------------------------------------------
- bool ExtractParameters( int argc, char* argv[],
- IXceedEncryptionPtr piEncrypt,
- _bstr_t& bstrInputFileName,
- _bstr_t& bstrOutputFileName )
- {
- // These variables used to initialize the Encryption Method property
- // are set, here, to their default values.
- SEncryptionMethod* pxMethod = g_pxEncryptionMethods;
-
- bool bFound;
-
- // We parse each command line parameter
- int i = 0;
- while( ++i < argc )
- {
- if( argv[ i ][ 0 ] == '/' )
- {
- // The parameter starts with a /
- // Meaning it's an option parameter
- switch( argv[ i ][ 1 ] )
- {
- case 'm':
- case 'M':
- // The user wants to set the encryption method
- bFound = false;
-
- // We go through all the encryption methods in the
- // correspondence table, stopping when we find a
- // match.
- for( pxMethod = g_pxEncryptionMethods;
- pxMethod->pszCommandLine != NULL;
- pxMethod++ )
- {
- if( lstrcmpi( argv[ i ] + 2, pxMethod->pszCommandLine ) == 0 )
- {
- bFound = true;
- break;
- }
- }
-
- if( !bFound )
- {
- printf( "Invalid encryption method '%s'\n\n", argv[ i ] );
- return false;
- }
-
- break;
-
- default:
- printf( "Unknown command '%s'\n\n", argv[ i ] );
- // Continue
- case 'h':
- case 'H':
- case '?':
- return false;
- }
- }
- }
-
- // Check if the user provided an output file name
- if( argc < 3 || argv[ argc - 1 ][ 0 ] == '/' || argv[ argc - 2 ][ 0 ] == '/' )
- {
- printf( "You did not specify a passphrase or an output filename\n\n" );
- return false;
- }
- else if( argc < 4 || argv[ argc - 3 ][ 0 ] == '/' )
- {
- // Only an output file was specified
- bstrOutputFileName = argv[ argc - 1 ];
- }
- else
- {
- // Both input and output file were specified
- bstrInputFileName = argv[ argc - 3 ];
- bstrOutputFileName = argv[ argc - 1 ];
- }
-
- _bstr_t bstrPassPhrase = argv[ argc - 2 ];
-
-
- // According the encryption method chosen by the user, we set the various
- // properties of an encryption method and prepare the
- // Encryption interface (piEncrypt).
-
- // The properties common to all encryption method are:
- // EncryptionMode
- // The methods common to all encryption method are:
- // SetSecretKeyFromPassPhrase, SetRandomInitVector
-
- // For each encryption method, we begin by creating a temporary instance
- // of the appropriate encryption method. The properties of this instance
- // are then set and the instance is assign to the EncryptionMethod property
- // of the XceedEncryption instance. This adds a reference to the
- // Encryption method instance so that the instance will not be freed
- // when it will fall out of scope.
-
- switch( pxMethod->eMethod )
- {
- case emRijndael :
- {
- IXceedRijndaelEncryptionMethodPtr piRijndaelMethod;
-
- piRijndaelMethod.CreateInstance( CLSID_XceedRijndaelEncryptionMethod );
-
- // Set the Secret key using the pass phrase specified on the command prompt.
- piRijndaelMethod->SetSecretKeyFromPassPhrase( bstrPassPhrase, KEY_SIZE );
-
- // We encrypt the file in CBC mode, which is more secure than ECB mode.
- piRijndaelMethod->EncryptionMode = emoChainedBlocks;
- piRijndaelMethod->SetRandomInitVector();
-
- piEncrypt->EncryptionMethod = IXceedEncryptDataPtr( piRijndaelMethod );
- }
- break;
-
- case emTwofish :
- {
- IXceedTwofishEncryptionMethodPtr piTwofishMethod;
-
- piTwofishMethod.CreateInstance( CLSID_XceedTwofishEncryptionMethod );
-
- // Set the Secret key using the pass phrase specified on the command prompt.
- piTwofishMethod->SetSecretKeyFromPassPhrase( bstrPassPhrase, KEY_SIZE );
-
- // We encrypt the file in CBC mode, which is more secure than ECB mode.
- piTwofishMethod->EncryptionMode = emoChainedBlocks;
- piTwofishMethod->SetRandomInitVector();
-
- piEncrypt->EncryptionMethod = IXceedEncryptDataPtr( piTwofishMethod );
- }
- break;
- }
-
- return true;
- }
-
-
- //
- // END_OF_FILE
- //
-