Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds constant time equal functions for strings and bytes #14

Closed
wants to merge 1 commit into from

Conversation

janilcgarcia
Copy link

@janilcgarcia janilcgarcia commented May 13, 2019

Hoping to help with #13 to avoid timing attacks on hashes and other comparisions.
I'm not sure how to write tests to make sure the functions are constant time, but I'm pretty sure they are, please review, tho.

let l = len a in
let lst = List.init l (fun x -> x) in
let fold acc i =
acc && (eq a b i) in
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there is a difference in the middle of the string, then for bytes after that point, eq will no longer be called (because && is a "short-circuiting" operator). This will be a small difference, but may still be detectable with high resolution timing attacks or cache-line shenanigans.

@xavierleroy
Copy link
Owner

Thanks for taking a stab at this problem. Here is an implementation, based on @wiml's comment in #13, that should be constant-time:

let seq_equal (len: 'a -> int) (get: 'a -> int -> char) (s1: 'a) (s2: 'a) =
  let l = len s1 in
  let rec equal i accu =
    if i >= l
    then accu = 0
    else equal (i + 1)
               (accu lor ((Char.code (get s1 i)) lxor (Char.code (get s2 i))))
  in
    l = len s2 && equal 0 0

let string_equal = seq_equal String.length String.get
let bytes_equal = seq_equal Bytes.length Bytes.get

@xavierleroy
Copy link
Owner

I went ahead and committed the implementation above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants