You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Adding a constEq (or similar) function for security use cases #697
To prevent timing attacks, sometimes you'd want to compare bytes (like hashes) in constant time, since this can give the attacker information on how far they have matched the bytes.
This is a semi-quick example of what it might/would look like (did not compile, might have errors)
(based it off of constEq from the memory package)
constEq::ByteString->ByteString->Bool
constEq (BS fptr1 len1) (BS fptr2 len2)
| len1 /= len2 =False|otherwise= accursedUnutterablePerformIO $do
withForeignPtr fptr1 $\ptr1 ->
withForeignPtr fptr2 $\ptr2 ->let loop i !acc
| i == len1 =pure$! acc ==0|otherwise=do
mZero <- xor <$> peekByteOff i ptr1 <*> (peekByteOff i ptr2 ::IOWord8)
loop (i +1) (acc .|. mZero)
in loop 00
I think such "security" use-cases belong in memory, crypton and the like, more than in bytestring.
A sufficiently clever compiler might still optimise the above to return early as soon as the first difference is detected.
In realistic applications there should be a priori modest size limit on the bytes to compare, and an FFI call to a constant-time comparison in C is typically a better option.
Activity
vdukhovni commentedon Oct 25, 2026
I think such "security" use-cases belong in
memory,cryptonand the like, more than inbytestring.A sufficiently clever compiler might still optimise the above to return early as soon as the first difference is detected.
In realistic applications there should be a priori modest size limit on the bytes to compare, and an FFI call to a constant-time comparison in C is typically a better option.