[Botan-devel] Caching derived keys

Jack Lloyd lloyd at randombit.net
Sun Feb 15 16:34:31 EST 2009

On Fri, Feb 13, 2009 at 10:27:37PM +0000, Magnus Therning wrote:

> I've been playing with botan, hoping to replace my use of python-crypto
> in a python app I've written.  I only need very simply encrypt/decrypt
> and my class currently looks like this:
>   class Crypto {
>       public:
>           Crypto(std::string pwd);
>           ~Crypto();
>           boost::python::tuple encrypt(std::string pt);
>           std::string decrypt(std::string salt, std::string ct);
>   };
> At first I attempted to cache the derived key, but ran into
> memory/instance ownership issues.  The botan API seems to like passing
> ownership with arguments and to clean up on method exit.  That made
> caching difficult so I now derive the key on each call to
> encrypt/decrypt.  Is there something obvious that I've missed, is it
> actually really simple to "pre-derive" the key?

This would depend somewhat on what exactly you are doing inside this
class, but I'm guessing based on the constructor that you are doing
some sort of password-based encryption, for example hashing the
password with PBKDF2 to generate the key.

So there are actually multiple levels of caching possible here:

1) When you call derive_key, you can copy the returned value to a
   member of your Crypto class. This avoids having to go through the
   (intentionally) slow PBKDF2 operation each time. This key can be
   saved/copied around/etc without much complication.

2) I assume you are setting up a pipe object with some set of filters
   for handling encryption/MACing, etc. This object could also be
   cached. This would avoid repeated memory allocations, plus
   rerunning the key schedule (which depending on the algorihthm could
   make a big difference). However doing so woul prevent copying since
   Pipe cannot be copied (but if you needed to copy your crypto object
   for some reason you could simply cache both the Pipe and the
   password-derived key, and writing a copy constructor and assignment
   operator for Crypto that initialize a new set of filters using the

Hope this helps. It would be easier to provide specific advice if you
could send the source for your class.


More information about the botan-devel mailing list