← Back to team overview

openstack team mailing list archive

Re: make swift.common.utils.streq_const_time more efficient

 

That function's purpose is to compare strings without
short-circuiting, to foil timing attacks against token comparisons or
similar.


On Thu, Sep 13, 2012 at 1:28 AM, Mike Green <iasybvm@xxxxxxxxx> wrote:
> def streq_const_time(s1, s2):
>
>     if len(s1) != len(s2):
>         return False
>     result = 0
>     for (a, b) in zip(s1, s2):
>         result |= ord(a) ^ ord(b)
>     return result == 0
>
> +++++++++++++++++++++++++++++++++++++++++
>
> If s1 and s2 are of the same length,  then the function will compare every
> characters in them.  I think it may be more efficient as follow:
>
> def streq_const_time(s1, s2):
>
>     if len(s1) != len(s2):
>         return False
>     result = 0
>     for (a, b) in zip(s1, s2):
>         if ord(a) ^ ord(b):
>           return False
>     return True


References