I'm writing a function to act as a cryptographic hash of a number within a range that returns another number of the same range. The catch is that the result needs to have certain properties. I run a simple test for these properties and call the function recursively if the test fails. Naturally this raises a red flag for a timing attack, however, the test is performed on the result of a hash only. Everything preceding the hash takes exactly the same amount of time regardless of input.

My question is, is this a harmful leak of information? Here's the function in question.

def numhash(num, maxnum):
    num = sha256(str(num)).hexdigest() # calculate sha256 of string version of number
    num = int(num, 16) % maxnum # convert this to an integer and mod it by the top bound of the range (exclusive)
    if bin(num).count('1') % 2: return numhash(num + 1) # check for an even number of 1 bits in the number, reject and try again if true. This is where the timing issue is caused
    return num

Note: I'm aware of the slight bias towards lower results and high collision rate. This is acceptable.

  • 2
    $\begingroup$ Much worse problem than side channel attack: when iterating, it is with num set to (int((sha256(str(num)).hexdigest()),16)%maxnum)+1 rather than the apparently intended num+1, which is from a set of at most maxnum values, and we are not sure that this terminates. $\;$ If the criteria is even parity, why not generate the low-order bit from the top ones, avoiding iteration, and recursion? Evenness for odd maxnumrequires care, though. $\;$ Also: str(num) is quite likely to have a timing side channel. Just don't code crypto primitives in high-level languages ! $\endgroup$ – fgrieu Oct 5 '15 at 6:40
  • $\begingroup$ I would argue that it is high level APIs that are the problem rather than high level languages, since e.g. printf or even itoa has similar issues as str. Plus, don't code primitives, period, if you can help it. $\endgroup$ – otus Oct 5 '15 at 7:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.