i was finally able to encrypt files and have the code attached
i just changed algo name in  cbcmode to aes and then des and then
blowfish

i just wanted to ask a simple question now, the encrypted sinks of
each algorithm have same sizes, is this right or i have done some
mistake?
cause  my project is regarding space computation (memory taken by each
algorithm in each mode) and time taken for encrypting large files

also, i changed cbc to ecb mode it crashed... any suggestions

please reply as you are the only active member

qt 4.6
cryptopp 5.5.2
win7


/// code below

#define CRYPTOPP_DEFAULT_NO_DLL
#include <cryptopp/dll.h>
#ifdef CRYPTOPP_WIN32_AVAILABLE
#include <windows.h>
#endif


#include <iostream>
#include <string>
#include <cstdio>
#include <sstream>
#include <cryptopp/config.h>
#include <cryptopp/hex.h>
#include <cryptopp/files.h>
#include <cryptopp/cryptlib.h>
#include <cryptopp/modes.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <cryptopp/aes.h>
#include <cryptopp/des.h>
#include <cryptopp/blowfish.h>

USING_NAMESPACE(CryptoPP)
USING_NAMESPACE(std)
const int MAX_PHRASE_LENGTH=250;

using std::ostringstream;
using std::string;
using std::cout;
using std::endl;

static bool isHex(string checkForHex) {
        size_t found;
        found = checkForHex.find_first_not_of("0123456789ABCDEF");
        if (found!=string::npos) {
                // This string has non-hex characters in it
                return false;
        } else {
                // only hex characters
                return true;
        }
}


static string HexDecode(string hexString)
{
        if (isHex(hexString)) {
                string binaryString;
                StringSource(hexString, true, new HexDecoder(new
StringSink(binaryString)));
                return binaryString;
        } else {
                // it's already binary!
                return hexString;
        }
}


static string HexEncode(string binaryString) {

        if (isHex(binaryString)) {
                // This string is already hex, don't convert it!
                return binaryString;
        } else {
                string hexString;
                StringSource(binaryString, true, new HexEncoder(new
StringSink(hexString)));
                return hexString;
        }
}

static string ByteGen(int howManyBytes) {
        // returns a new random key of the given byte length
        AutoSeededRandomPool rnd;
        byte block[howManyBytes];
        rnd.GenerateBlock(block, howManyBytes);
        string blockString;
        blockString.assign((char *)block, sizeof(block));
        return blockString;
}

static string BitGen(int howManyBits) {
        // returns a new random key in binary of the given bit length
        int byteLength = howManyBits/8; // bitLengths always better be
div 8!!
        return ByteGen(byteLength);
}



static string hashSHA256(string inputString) {
        // returns a SHA-256 encoded hash of the inputString in binary
        // always returns 256 bits
        SHA256 hash;
        byte digest [ SHA256::DIGESTSIZE ];

        hash.CalculateDigest( digest, (byte *)inputString.c_str(),
inputString.length() );
        string hashString;
        hashString.assign((char *)digest, sizeof(digest));

        return hashString;
}



static void EncryptFileAES(istream& inFile, ostream& outFile, string
key, string iv, bool &err, string &errMsg) {
        // will encrypt the file at filenameIn to filenameOut using
AES
        // WARNING: The iv must be known and retained for decryption!!
        // key and iv can be hex or binary


        // convert the key and iv
        key = HexDecode(key);
        iv = HexDecode(iv);
        try {
                // Set up the encrypter
            CBC_Mode< CryptoPP::AES >::Encryption e1( (byte
*)key.c_str(), key.length(), (byte *)iv.c_str() );
                // encrypt
                //if (filenameOut == "cout")
                //      FileSource( filenameIn.c_str(), true, new
StreamTransformationFilter( e1, new FileSink(cout)));
                //else
                        FileSource( inFile, true, new
StreamTransformationFilter( e1, new FileSink(outFile)));
                err= false;
                return;
        } catch (Exception& e) {
                errMsg = e.GetWhat();
                err = true;
                return;
        }
}


static void DecryptFileAES(istream& inFile, ostream& outFile, string
key, string iv, bool &err, string &errMsg) {
        // will encrypt the file at filenameIn to filenameOut using
AES
        // WARNING: The correct iv MUST be provided
        // key and iv can be hex or binary

        // convert the key and iv
        key = HexDecode(key);
        iv = HexDecode(iv);

        try {
                // Set up the encrypter

            CBC_Mode< CryptoPP::AES>::Decryption d ( (byte
*)key.c_str(), key.length(), (byte *)iv.c_str() );
                // encrypt
                //if (filenameOut == "cout")
                //      FileSource( filenameIn.c_str(), true, new
StreamTransformationFilter( d, new FileSink(cout)));
                //else
                        FileSource( inFile, true, new
StreamTransformationFilter( d, new FileSink(outFile)));
                err= false;
                return;
        } catch (Exception& e) {
                errMsg = e.GetWhat();
                err = true;
                return;
        }
}



int main (int argc, char * const argv[])
{
        bool err;
        string errMsg;

    AutoSeededRandomPool rng;


    string key3(AES::DEFAULT_KEYLENGTH, 0);
    string iv3(AES::BLOCKSIZE, 0);// this is the Initialization
Vecktor

  //Create a random key as well as a random IV with default sizes (16)
    rng.GenerateBlock((unsigned char*)key3.c_str(),
AES::DEFAULT_KEYLENGTH);
    rng.GenerateBlock((unsigned char*)iv3.c_str(), AES::BLOCKSIZE);



    // Now encrypt it with the MR methods
    // First open the infile
    ifstream infile("C:\\Qt\\abc.mp3", ios::binary); // always open
your files in binary mode!

    // Now the outfile, this can be any outstream, but we'll save to
disk first
    ofstream outfile("C:\\Qt\\example.txtcrypt", ios::binary);
    ofstream outfile2("C:\\Qt\\abc2.mp3",ios::binary);

    // encrypt it!
    EncryptFileAES(infile,outfile,key3,iv3,err,errMsg);
    //BasicCryptoPPWrap::MREncryptFileAES(infile, outfile, key2,  err,
errMsg);
    if (err) {
            cout << errMsg << "\n";
            return -1;
    }

    infile.close();
    outfile.close();

    // delete the old text file
    //remove("SecretSteakRecipe.txt");

    // Now we'll decrypt, but do it to memory so we leave no trace!
    stringstream outBuffer;
    infile.open("C:\\Qt\\example.txtcrypt", ios::binary);

    // Decrypt it!
    DecryptFileAES(infile, outfile2, key3,iv3,  err, errMsg);
    if (err) {
            cout << errMsg << "\n";
            return -1;
    }

    // close and delete the encrypted file (you don't want me leaving
files all over your hard drive do you?)
    infile.close();
    outfile2.close();

}

// code ends

On Sep 11, 11:20 am, GrimReaper <[email protected]> wrote:
> I am running qt 4.6,mingw compiler
> windows 7
> cryptopp 5.5.2 version
>
> The file was corrupted in a way that i decrypted that the image only
> top part of it was decrypted right(1/7th part of image form top
> recovered)(total image size7 kb) rest was blank
>
> on bigger images it corrupted
>
> I am not much in security i just wanted to pass infile outfile
> password and it should returned encrypted file and decvrypted file, i
> am trying to do that with aes , des ,triple des blowfish
>
> for aes
>
> i tried this link, its the code for aes file encryption and this is
> working very good with full 
> decryptionhttp://swarmapps.wordpress.com/2009/11/24/a-simplification-wrapper-fo...
>
> if you can tell me how to convert this for blowfish , this might help
> i need not dwelve into much details
>
> Thank you for your reply
>
> On Sep 11, 11:11 am, GrimReaper <[email protected]> wrote:
>
> > exception is thrown that decryption failed
>
> > i tried with small files(1kb or less it worked like a charm)
>
> > but size greater than that failed , with throwing exception that
> > decryption failed
>
> > On Sep 10, 10:38 pm, Mike Hamburg <[email protected]> wrote:
>
> > > grimreaper,
>
> > > We can probably help you on this list, but you'll need to provide more
> > > information than this.  The code that was provided ought to work equally
> > > well for text and binary, so let's try to figure out what's wrong with
> > > your example.
>
> > > In what way does decryption fail?
>
> > > Does it throw an exception?  What exception?
>
> > > Does it produce a corrupt file?  In what way is the file corrupt?  (That
> > > is, in what way is it different from the original file?)  Does it have
> > > its CR's replaced with CRLF's?  Does it have null bytes removed?  Is it
> > > the same size or a different size?  Does it have random junk at the
> > > beginning or end?  Does it fail in the same way every time, or does it
> > > depend on the random "IV" block?  Does the output file just have the
> > > wrong extension (.txt) for your OS to open it?
>
> > > What OS are you running (Windows, right?  What version?), and what
> > > version of Crypto++?
>
> > > Cheers,
> > > MikeOn Fri, 2010-09-10 at 00:45 -0700, grimreaper wrote:
>
> > > > Mouse-2 wrote:
>
> > > > > #include <iostream>
>
> > > > > #include <cryptopp/aes.h>
> > > > > #include <cryptopp/modes.h>
> > > > > #include <cryptopp/sha.h>
> > > > > #include <cryptopp/osrng.h>
> > > > > #include <cryptopp/files.h>
> > > > > #include <cryptopp/filters.h>
>
> > > > > USING_NAMESPACE(CryptoPP);
> > > > > USING_NAMESPACE(std);
>
> > > > > /**************************************************************/
> > > > >   /* Code to illustrate usage of cryptographic primitives     */
> > > > >   /* provided by Crypto++ library v5.5.1 of Wei Dai.          */
> > > > >   /*                                                          */
> > > > >   /* In particular, the program provides two functions:       */
> > > > >   /*                                                          */
> > > > >   /* 1. Encrypt a file (key based on password) with random IV;*/
> > > > >   /*                                                          */
> > > > >   /* 2. Decrypt previously encrypted file.                    */
> > > > >   /*                                                          */
> > > > >   /* Issue with the original code:                            */
> > > > >   /*     - set IV in the encryptor but also used it as random */
> > > > >   /*       prefix, so garbage was the 1st encrypted block;    */
> > > > >   /*     - did not "fast-forward" the encrypted file past the */
> > > > >   /*       first block (which was encrypted random garbage).  */
> > > > >   /*                                                          */
> > > > >   /* Corrections performed:                                   */
> > > > >   /*     - fixed encryptor by leaving random block prefixed,  */
> > > > >   /*       but removing redundancy (having it in encryptor);  */
> > > > >   /*     - fixed decryptor (see the source code).             */
> > > > >   /*                                                          */
> > > > >   /*==========================================================*/
> > > > >   /* Written by:                                              */
> > > > >   /*                   Rash <[email protected]>            */
> > > > >   /*                                                          */
> > > > >   /* Modified by:                                             */
> > > > >   /*                   Mouse <[email protected]>        */
> > > > >   /*                   Sun Sep 2, 12:25:00 2007               */
> > > > >   /*                                                          */
> > > > >   /************************************************************/
> > > > >   /*                                                          */
> > > > >   /* Copyright (C) 2007 Rash  <[email protected]>          */
> > > > >   /* Copyright (C) 2007 Mouse <[email protected]>       */
> > > > >   /*                                                          */
> > > > >   /************************************************************/
>
> > > > > void encryptFile(const char* password, const char* inputFileName,
> > > > >                const char* outputFileName)
> > > > > {
> > > > >   byte pass[AES::BLOCKSIZE];  // digest of password
> > > > >   byte iv[16];                        // Initial Vector (IV),  misused
> > > > >                                 // by original author
> > > > >   byte true_iv[16];             // real IV used - set to zero
>
> > > > >   AutoSeededRandomPool rng;
>
> > > > >   // digest password
> > > > >   StringSource(password, true,
> > > > >              new HashFilter(*(new SHA256),
> > > > >                             new ArraySink(pass, AES::BLOCKSIZE)));
>
> > > > >   // random Initial Vector
> > > > >   rng.GenerateBlock(iv, 16);
> > > > >   memset(true_iv, 0, 16);
>
> > > > >   // create object for encrypting
> > > > >   AES::Encryption aesEncryption(pass,
> > > > >                               CryptoPP::AES::DEFAULT_KEYLENGTH);
> > > > >   CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption,
> > > > >                                                   true_iv);
>
> > > > >   StreamTransformationFilter *encryptor;
> > > > >   encryptor = new StreamTransformationFilter(cbcEncryption,
> > > > >                                            new 
> > > > > FileSink(outputFileName) );
>
> > > > >   encryptor->Put(iv, 16); // this prefixes the file with random block 
> > > > > (not
> > > > > IV)
> > > > >                  // Cryptographically it is equivalent to IV, so just 
> > > > > as
> > > > > good
>
> > > > >   // "bind" a file and encrypt one
> > > > >   FileSource(inputFileName, true, encryptor);
> > > > > }
>
> > > > > void decryptFile(const char* password, const char*inputFileName,
> > > > >                const char* outputFileName)
> > > > > {
> > > > >   byte pass[AES::BLOCKSIZE];
> > > > >   byte iv[16];        // here's 1st problem: AES IV is 16 bytes
> > > > >   byte head_file[16]; // so must skip 16 bytes, not 8.
>
> > > > >   memset(iv, 0, 16); // very correct - in fact the encryptor prefixes 
> > > > > file
> > > > >   // with a random block, so no need to pass the IV explicitly.
>
> > > > >   try {
> > > > >     StringSource(password, true, new HashFilter(*(new SHA256), new
> > > > >                                               
> > > > > ArraySink(pass,AES::BLOCKSIZE)));
>
> > > > >     CryptoPP::AES::Decryption aesDecryption(pass,
> > > > >                                           
> > > > > CryptoPP::AES::DEFAULT_KEYLENGTH);
> > > > >     CryptoPP::CBC_Mode_ExternalCipher::Decryption
> > > > > cbcDecryption(aesDecryption, iv);
>
> > > > >     StreamTransformationFilter *decryptor;
> > > > >     decryptor = new
> > > > >       StreamTransformationFilter(cbcDecryption, new
> > > > >                                FileSink(outputFileName));
>
> > > > >     // decryptor->Get(head_file, 16); // does not do anything useful,
> > > > > wrong here
> > > > >     // We must somehow decrypt 1st block of the input file, without
> > > > > sending the
> > > > >     // result into the output file.
> > > > >     char garbage[16], iv_garbage[16]; // place for IV stuff
> > > > >     ifstream inf;
> > > > >     inf.open(inputFileName); inf.read(iv_garbage, 16); // absorb 
> > > > > random
> > > > > prefix
>
> > > > >     // Decrypt random prefix (with zero IV) to some dummy buffer to 
> > > > > get
> > > > >     // (a) decryptor state adjusted to IV, and
> > > > >     // (b) file position pointer advanced to the past-IV spot.
> > > > >     cbcDecryption.ProcessData((byte *)garbage, (const byte 
> > > > > *)iv_garbage,
> > > > > 16);
>
> > > > >     // NOW can run the decryption engine in "automatic" mode
> > > > >     FileSource(inf, true, decryptor);
>
> > > > >     inf.close(); // to be nice
> > > > >   }
> > > > >   catch(CryptoPP::Exception &e)
> > > > >     {
> > > > >       cerr << "Caught exception during decryption!" << endl;
> > > > >       return;
> > > > >     }
> > > > > }
>
> > > > > int main(int argc, char *argv[])
> > > > > {
> > > > >   const char *pwd  = "not-so-complicated parole";
> > > > >   const char *pfn = "plain.txt";
> > > > >   const char *cfn =
>
> ...
>
> read more »

-- 
You received this message because you are subscribed to the "Crypto++ Users" 
Google Group.
To unsubscribe, send an email to [email protected].
More information about Crypto++ and this group is available at 
http://www.cryptopp.com.

Reply via email to