Reputation: 989
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.
Upvotes: 2
Views: 149
Reputation: 94038
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.
Upvotes: 1