Feb 18, 2010

How do you unit test encryption?


I wrote two extenders to be used on the string type.
So you can say "test".Encrypt() and "encrpyptedtest".Decrypt().

I was wondering how to unit test this thing.
The first approach which was really obvious was to encrypt the string and then decrypt it, if you get the string before you do those two actions on it - the encryption is correct.

The question in this approach is : What do you test? do you test the encryption or the decryption?
You can get a false positive result this way. For example if the Encrypt method returns the same string without changing it and the Decrypt method returns the same string without changing it - the test will be passed (the string after encrypt -> decrypt will be the same as it was before).

The other approach is to hardcode encrypted and decrypted string, then pass the decrypted string to the Encrypt() method and see if the result matches the encrypted string.
Then pass the encrypted string to the Decrypt test method and see if it matches the decrypted string.
The question here is "What happens if someone change either the key or the initialization vector for the encryption?".
The test will fail as the strings no longer match (unless you are very very lucky to hit some collision case :), but the methods are valid and they work correctly.

For now - I will use the second method. I will hardcode an encrypted / decrypted pair as well as the key and the IV used for the encryption / decryption.
I will first check if the key and the vector match the one that were used to generate the pair and if they don't - the test will be inconclusive so the guy who changed either the key or the vector can easilly find the problem and resolve it.

Anyway I am really interested in how would you do such a task?