[Cryptography] Implementing constant-time string comparison

Ben Laurie ben at links.org
Wed Jun 18 17:25:57 EDT 2014


On 18 June 2014 22:17, sycamoreone <sycamoreone at riseup.net> wrote:
> Ben Laurie:
>> On 17 June 2014 20:36, sycamoreone <sycamoreone at riseup.net> wrote:
>>> Why are other libraries not doing this? That is, is this
>>> paranoid, or merely taking constant-time serious? Or does the
>>> 'unusual' return statement serve another purpose?
>>>
>>> For reference I added the code of some other implementations
>>> below.
>>
>> You seem to be saying that other libraries are doing this?
>
> I don't really understand what you are asking? I meant that, to the best
> of my knowledge, the posted code is what Keyzar and OpenSSL are using
> for comparison of byte arrays.
>
> I would like to know if the different ways to handle the return value
> are a matter of taste, or if one is clearly better or "right".

Ah! I had misunderstood your issue - I thought you were complaining
about the lack of constant time implementations, but actually, you are
complaining about uniform return values.

In this case there's a tradeoff between speed and exactness. Choose your poison.

>>> OpenSSL passes the problem on to the user of the library:
>>
>> By "the problem", I presume you mean the issue of getting 0 or 1
>> out of this. In general, the style is if (CRYPTO_memcmp(...)) (or !
>> that), so 0 or 1 is not needed.
>
> Yes. I also could have said "decision". If there is an issue with the
> comparison d==0 at all, then it is likely that if (CRYPTO_memcmp(...))
> will have the same issues; again this of course depends on the code
> generated by the compiler.

It would be a weird compiler that caused a problem for this case.

Some languages (e.g. Python) promote the idea of truthy and falsy. Not
directly comparable but usable as booleans. C/C++ are open on the
question, of course.

>> But I admit to once being bitten in the ass comparing "booleans"
>> that weren't (in this case bitfields, though), so I can agree it
>> isn't best practice.
>
> No. It puts another burden on the user of the library.

It depends on expectations.


More information about the cryptography mailing list