Search code examples
crypto++

how to encrypt data using Cryptopp::TEA?


I've been searching for a while and couldn't find any document about CryptoPP::TEA encrypting.

Anyone know how to encrypt data using CryptoPP::TEA?

Thanks.


Solution

  • Anyone know how to encrypt data using CryptoPP::TEA?

    Crypto++ provides implementations for TEA and XTEA. I recall there can be some interop problems because there's a newer TEA variant (but I don't recall the details).

    TEA and XTEA are just block ciphers, so they can be used like any other block cipher (such as 3DES, AES or Cameilla). Because it can be used like any other block cipher, the code below is from Crypto++'s CBC Mode wiki page. All I did was change AES to TEA.

    Here is the output of the program:

    $ ./cryptopp-test.exe
    plain text: CBC Mode Test
    cipher text: 483ABA61693D885532604E376703A91D
    recovered text: CBC Mode Test
    

    And here is the program:

    AutoSeededRandomPool prng;
    
    SecByteBlock key(TEA::DEFAULT_KEYLENGTH);
    prng.GenerateBlock( key, key.size() );
    
    byte iv[ TEA::BLOCKSIZE ];
    prng.GenerateBlock( iv, sizeof(iv) );
    
    string plain = "CBC Mode Test";
    string cipher, encoded, recovered;
    
    /*********************************\
    \*********************************/
    
    try
    {
        cout << "plain text: " << plain << endl;
    
        CBC_Mode< TEA >::Encryption e;
        e.SetKeyWithIV( key, key.size(), iv );
    
        StringSource ss(plain, true,
                            new StreamTransformationFilter( e,
                                new StringSink( cipher )
                            ) // StreamTransformationFilter
                        ); // StringSource
    }
    catch( const CryptoPP::Exception& e )
    {
        cerr << e.what() << endl;
        exit(1);
    }
    
    /*********************************\
    \*********************************/
    
    // Pretty print cipher text
    StringSource ss(cipher, true,
                        new HexEncoder(
                            new StringSink( encoded )
                        ) // HexEncoder
                    ); // StringSource
    
    cout << "cipher text: " << encoded << endl;
    
    /*********************************\
    \*********************************/
    
    try
    {
        CBC_Mode< TEA >::Decryption d;
        d.SetKeyWithIV( key, key.size(), iv );
    
        StringSource ss(cipher, true, 
                            new StreamTransformationFilter( d,
                                new StringSink( recovered )
                            ) // StreamTransformationFilter
                        ); // StringSource
    
        cout << "recovered text: " << recovered << endl;
    }
    catch( const CryptoPP::Exception& e )
    {
        cerr << e.what() << endl;
        exit(1);
    }