Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / C

Authenticated Encryption

Rate me:
Please Sign up or sign in to vote.
5.00/5 (34 votes)
23 Mar 2009CPOL23 min read 131.9K   767   145  
Perform authenticated encryption with Crypto++.
// Sample.cpp
//

#include "stdafx.h"

#include "osrng.h"
using CryptoPP::AutoSeededRandomPool;

#include "filters.h"
using CryptoPP::StringSink;
using CryptoPP::StringSource;
using CryptoPP::AuthenticatedEncryptionFilter;
using CryptoPP::AuthenticatedDecryptionFilter;

#include "aes.h"
using CryptoPP::AES;

#include "ccm.h"
using CryptoPP::CCM;

int main(int argc, char* argv[])
{
    AutoSeededRandomPool rng;

    byte key[AES::DEFAULT_KEYLENGTH];
    rng.GenerateBlock( key, sizeof(key) );
    byte iv[AES::BLOCKSIZE];
    rng.GenerateBlock( iv, sizeof(iv) );

    string plaintext = "Licenses: 10";
    string ciphertext, recovered;

    const int TAG_SIZE = 12; // 96 bit authenticator

    try
    {
        CCM<AES,TAG_SIZE>::Encryption encryptor;
        encryptor.SetKeyWithIV(key, sizeof(key), iv);
        encryptor.SpecifyDataLengths( 0, plaintext.size() );

        StringSource( plaintext, true,
            new AuthenticatedEncryptionFilter(
                encryptor,
                new StringSink( ciphertext )
            )
        );

        ///////////////////////////////////
        // Tamper
        // ciphertext[10] ^= 0x01;
        //
        ///////////////////////////////////

        CCM<AES, TAG_SIZE>::Decryption decryptor;
        decryptor.SetKeyWithIV(key, sizeof(key), iv);
        decryptor.SpecifyDataLengths( 0, ciphertext.size()-TAG_SIZE );

        StringSource( ciphertext, true,
            new AuthenticatedDecryptionFilter(
                decryptor,
                new StringSink( recovered )
            )
        );

        cout << "Recovered: " << recovered << endl;
    }
    catch( const exception& e )
    {
        cerr << "Error: " << e.what() << endl;
    }

    return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Systems / Hardware Administrator
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions