When cryptography is involved, a major rule is king: never write your own cryptography code. Well if this is the case why am I writing my own constant time comparisons in .NET?
StackOverflow took down my post as “Opinion based” so I’m posting it here so it doesn’t end up delisted on Google. I should probably do a write-up on why I struggle to contribute to StackOverflow at some point…
Constant-time comparisons are extremely important in cryptography code. A normal comparison will bail early from the comparison process if a mismatch is found, however this can leak information about how many bytes you got right before the comparison failed. If you’re guessing some kind of key (eg: comparing an API key), this can be catastrophic.
There are currently two open implementations for constant-time comparison methods, one in BouncyCastle and one in SecurityDriven.Inferno:
https://github.com/sdrapkin/SecurityDriven.Inferno/blob/cfba069191247c8e24b096fd0f2dd899b5a25747/Utils.cs – SecurityDriven.Inferno.Utils.ConstantTimeEqual
http://securitydriven.net/inferno/ see: Constant-time Equality
My biggest hangup with SecurityDriven.Inferno is that ConstantTimeEqual will throw if the lengths aren’t the same. Throwing incurs a lot of overhead and disrupts program flow and I’d rather stay away from it. So generally your option is BouncyCastle (Edit: Lex pointed out below that BouncyCastle leaks the length of the byte array, so if that is a concern to you then Inferno is probably more of what you’re looking for).