0
$\begingroup$

Checks for null require an == check. If you have a string secret (say a hex-encoded key) and you want to check it's empty for validation should you compare it to "" in constant time?

You don't hear about constant time equals in these cases.

$\endgroup$
2
  • $\begingroup$ What does an "empty string" mean? One that is of zero length? Or, one that contains all zeros? Also, what language are we talking about? What access methods to the 'string' are available? $\endgroup$
    – poncho
    Jul 2, 2022 at 20:30
  • 5
    $\begingroup$ In the particular case of a key, I see no danger whatsoever in comparing it to the empty string or to null (if that differs). In all computer languages I know, at worse that leaks the result of the comparison, which is not dangerous, and precisely no other information about the key. Can you explain the context and why it's wanted to compare the string to "" in constant time, and what you are afraid could leak? Update: null and empty string are NOT the same as all-zero. $\endgroup$
    – fgrieu
    Jul 3, 2022 at 10:48

1 Answer 1

1
$\begingroup$

I presume this is referring to a language like Java or C# where checking for null parameters is commonplace. I'm also guessing reading a blog post/article like this has inspired this concern.

  1. The null check is recommended for good validation (e.g. to throw a handy exception message). IDEs can present warnings when you don't check for null.
  2. Cryptographic libraries in said languages include null checks.
  3. Constant time comparison functions usually check the lengths of the arrays being compared. This is equivalent to doing if (string.Length == 0) { return error; }.

In sum, it should be completely fine to check for null and whether the string is empty.

  • When it comes to checking if an array is all zeros, libsodium offers a constant time function for that.
  • When comparing a secret to any other secret (e.g. two passwords) or two authentication tags, you should always use a constant time function. When the lengths may be different, you can generate a random key and compare the HMAC of both secrets.
  • It's also sensible to use constant time hex functions, which are again available in libsodium.
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.