QuickCrypt Library C++ Interface

The following sample demonstrates how to use the CDES_EDE2 and CCounterMode classes to perform file encryption/decryption in Counter mode of operation.

#include <fstream>
#include <iostream>
#include <QuickCrypt.h>

using namespace std;
using namespace QuickCrypt;

// performs DES-EDE2 file encryption/decryption in Counter mode
bool EncryptDecryptFile( const char* filenamefrom, const char* filenameto, const unsigned char* iv, const unsigned char* key )
{
    //Open files

    fstream filefrom( filenamefrom, ios::in | ios::binary );
    
    if( !filefrom )
    {
        cout << "\nCould not open file: " << filenamefrom;
        return false;
    }

    fstream fileto( filenameto, ios::out | ios::binary );
    
    if( !fileto )
    {
        cout << "\nCould not open file: " << filenameto;
        return false;
    }

    //Instantiate CCounterMode object

    CCounterMode<CDES_EDE2> cipher( iv, key );

    //Encrypt/Decrypt file
    
    const unsigned int BUFF_SIZE = 1024;
    unsigned char buff[ BUFF_SIZE ];

    while( !filefrom.eof() )
    {
        filefrom.read( ( char* )buff, BUFF_SIZE );

        unsigned int buffsize = filefrom.gcount();

        cipher.Process( buff, buff, buffsize ); //in-place encryption/decryption

        fileto.write( ( char* )buff, buffsize );
    }

    return true;
}

int main()
{
    char buff[10];

    char filename[256];     //Initial file
    char filenameencr[256]; //Encrypted file
    char filenamedecr[256]; //Decrypted file

    //Define key, iv

    char key[CDES_EDE2::DEFAULTKEYSIZE] = 
    {
        's', 'e', 'c', 'r', 'e', 't', 'l', 'y',
        '9', '6', '7', '1', '2', '9', '2', '7'
    };

    unsigned char iv[CDES_EDE2::BLOCKSIZE] = 
    {
        0x41, 0x3E, 0xF0, 0xA1, 0xC6, 0x11, 0xE5, 0x50
    };

    do
    {
        //Get file to encrypt (Initial file)

        cout << "Enter the full name of the file to encrypt:\n";
        cin.getline( filename, 256 );

        //Get file to store the result of encryption (Encrypted file)

        cout << "Enter the full name of the file to store the result of encryption:\n";
        cin.getline( filenameencr, 256 );

        //Encrypt file

        if( EncryptDecryptFile( filename, filenameencr, iv, (const unsigned char*)key ) )
        {
            //Get file to store the result of decryption (Decrypted file)

            cout << "Enter the full name of the file to store the result of decryption:\n";
            cin.getline( filenamedecr, 256 );

            //Decrypt file

            EncryptDecryptFile( filenameencr, filenamedecr, iv, (const unsigned char*)key );

            //At this point compare Initial file with Decrypted file. They must be identical.
        }

        //Continue?
        
        cout << "\nContinue (Y/N)?";
        cin.getline( buff, 10 );

    } while( *buff == 'Y' || *buff == 'y' );

    return 0;
}

 


 

 

Send Feedback to SlavaSoft Inc. Tell a friend about QuickCrypt Library