March 24, 2019
Hot Topics:

Crypto++ Holds the Key to Encrypting Your C++ Application Data

  • May 15, 2006
  • By Victor Volkman
  • Send Email »
  • More Articles »

In C++ fashion, the FileSource constructor does all the work and then as EncryptFile() returns, the destructor cleans up after it. I don't think you can get any more object-oriented than this design—at least as far as declarative coding goes. The following are the four possible arguments used in this constructor:

FileSource (const char *filename,    // Our input filename line
            bool pumpAll,            // "drain" everything at once?
            BufferedTransformation *attachment=NULL,
            bool binary=true)        // Assume non-text data

In this case, you let binary mode default to true and create your own BufferedTransformation object with a new DefaultEncryptorWithMAC() call. A BufferedTransformation is an object that takes a stream of bytes as input (this may be done in stages), does some computation on them, and then places the result into an internal buffer for later retrieval. Any partial result already in the output buffer is not modified by further input. (A demonstration of blocking I/O is outside the immediate scope of this article.)

Now, take a closer look at the third argument in the FileSource constructor back on line #46:

...  new DefaultEncryptorWithMAC(passPhrase, new FileSink(out)));

Finally, you get to see the use of the passPhrase as sent down to the default encryptor, and you create a FileSink object that will open the output file and manage the buffering to the output file. Again, you could take manual control of the I/O buffering for performance or other reasons. At the end, you have a BufferedTransformation object with an encryptor and its corresponding Message Authentication Code as derived from the key.

To test the encryption/decryption, input the Constitution of the United States as the input file, store the intermediate encrypted file, and decrypt to test it as follows:

D:\crypto++>testcrypto.exe constitution.txt encrypt.txt
                           constitution2.txt Passphrase: Meathead
D:\temp\crypto++>dir *.txt
Directory of D:\temp\crypto++
04/06/2006  02:48 PM        28,365 constitution.txt
05/02/2006  03:54 PM        28,365 constitution2.txt
05/02/2006  03:54 PM        28,408 encrypt.txt

As you can see from the above test (and my own diffs later), the input and output files were identical and the intermediate file was precisely 43 bytes larger than the input or output. I would show you what the encrypted file looked like, but it is just so much random-looking data at that point.

Sign and Verify a File with RSA

Another easy-to-implement Crypto++ task is RSA signing and verification of files. RSA was named after its inventors Rivest, Shamir, and Adleman in 1977. RSA involves two keys: public key and private key (a key is a constant number later used in the encryption formula.) The public key is known to everyone and is used to encrypt messages. These messages can be decrypted only by use of the private key. In other words, anybody can encrypt a message, but only the holder of a private key can actually decrypt and read it.

RSA is also often used for signing messages. The most common example of this is protecting software license files from tampering while still keeping them human readable. In this case, the signature data is embedded as a hexadecimal string inside the license file. The function RSASignFile() in the following code takes a private key file and a message to be signed, and then writes the RSA signature to the final named file. To verify the file with RSAVerify(), you must supply the public key file, the message again, and its signature:

void RSASignFile(const char *privFilename,
                 const char *messageFilename,
                 const char *signatureFilename)
   FileSource privFile(privFilename, true, new HexDecoder);
   RSASSA_PKCS1v15_SHA_Signer priv(privFile);
   FileSource f(messageFilename, true, new SignerFilter(GlobalRNG(),
                priv, new HexEncoder(new FileSink(signatureFilename))));
bool RSAVerifyFile(const char *pubFilename,
                   const char *messageFilename,
                   const char *signatureFilename)
   FileSource pubFile(pubFilename, true, new HexDecoder);
   RSASSA_PKCS1v15_SHA_Verifier pub(pubFile)
   FileSource signatureFile(signatureFilename, true, new HexDecoder);
   if (signatureFile.MaxRetrievable() != pub.SignatureLength())
       return false;
       SecByteBlock signature(pub.SignatureLength());
   signatureFile.Get(signature, signature.size());
   VerifierFilter *verifierFilter = new VerifierFilter(pub);
   verifierFilter->Put(signature, pub.SignatureLength());
   FileSource f(messageFilename, true, verifierFilter);
   return verifierFilter->GetLastResult();

Crypto for Data Security

Beyond the obvious financial and military applications, cryptography can be used to store any information you would prefer not to leave accessible to everyone and everything. With seven million Americans reporting identity theft every year, any options you can give your users to increase their data security will surely make them breathe easier.

This article has barely scratched the surface of what Crypto++ can do for you. Perhaps its best aspect is that it can keep up with your needs for more sophisticated algorithms, ciphers, and compression, and thus provide a stable vehicle for your app to enter crypto-land.

About the Author

Victor Volkman has been writing for C/C++ Users Journal and other programming journals since the late 1980s. He is a graduate of Michigan Tech and a faculty advisor board member for Washtenaw Community College CIS department. Volkman is the editor of numerous books, including C/C++ Treasure Chest and is the owner of Loving Healing Press. He can help you in your quest for open source tools and libraries; just drop an e-mail to sysop@HAL9K.com.

Page 2 of 2

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date