2

Constant time & work evaluations of expressions are important to prevent side-channel attacks in cryptographic algorithms. However, I am not aware of any constant-time conversions between false/true and 0/1 in Java.

As a counter-example,

int x = p ? 1 : 0;

does not appear to have that property, since the branch in execution could mean there is a detectable difference in the evaluation of the expression. In C/C++,

int x = p;

would do the trick, but this implicit conversion is not allowed in Java. Is there a portable solution to this? Faster of course is better.

Note this is not the same as Convert boolean to int in Java because that question does not consider constant time.

Community
  • 1
  • 1
Warren MacEvoy
  • 898
  • 9
  • 14

1 Answers1

1

OK, don't vote for this answer yet as I don't have time to verify it, but I was thinking about:

public static int toIntConstantTime(final boolean b) {
    int x = 0;
    x |= b ? 0b01 : 0b10;
    x |= !b ? 0b10 : 0b01;
    return (x & ~(x >> 1)) & 0b01;
}

which makes the answer always perform the operation, performs the branch both ways and relies on both bits.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • I'll try and verify tomorrow (maybe Warren wants to give it a spin before that)... – Maarten Bodewes Mar 19 '17 at 01:21
  • Cool. Since there are different execution paths, the timing could still be different (code cache miss or the like). It would be nice if there is some answer that does not have differing paths. I'm starting to think that is impossible... – Warren MacEvoy Mar 19 '17 at 03:58
  • 1
    I actually ran into same problem. Your answer assumes being that the time differences due to branching in 2nd line will be offset by the one in the third making net timing difference 0. I still cannot rely on it as it may even be different in different JVM's and machines. – Manish Adhikari Jun 03 '22 at 07:00