Add ConstantTimeEq implementation for [T; N].#114
Add ConstantTimeEq implementation for [T; N].#114branlwyd wants to merge 2 commits intodalek-cryptography:mainfrom
Conversation
Only when the const-generics feature is enabled. I had to modify a few tests: they were relying on [u8; N] being automatically dereferenced into &[u8] to get the blanket ConstantTimeEq implementation for [T]. But once a blanket implementation is also available for [T; N], Rust attempts to use it instead & then complains that it can't compare arrays of different lengths. I suppose this technically counts as a backwards-compatibility break.
|
A few notes:
|
src/lib.rs
Outdated
| // This loop shouldn't be shortcircuitable, since the compiler | ||
| // shouldn't be able to reason about the value of the `u8` | ||
| // unwrapped from the `ct_eq` result. |
There was a problem hiding this comment.
If the compiler were sufficiently smart, if it noticed x became 0 it could short circuit the loop because anything & 0 is 0.
Why not just use a Choice? (or use the slice impl)
There was a problem hiding this comment.
I was wondering the same thing; I switched to falling back to the slice implementation. But the slice implementation uses literally the same code for its element-by-element comparison loop:
Lines 299 to 342 in 6b6a81a
If there's a problem with this code, there may be a pre-existing problem with the implementation for [T].
FWIW, I'm pretty comfortable falling back on the [T] implementation for the [T; N] implementation: a little experimentation showed that the Rust compiler can reason about slice lengths to optimize away length checks in similar code (but that's no guarantee that it will do so here, of course).
|
It's kind of crazy how it's able to use a different impl for I'm not sure where I stand on this being a breaking change or not. It definitely seems a lot more correct/type-safe for the impl for |
Only when the const-generics feature is enabled.
I had to modify a few tests: they were relying on [u8; N] being automatically dereferenced into &[u8] to get the blanket ConstantTimeEq implementation for [T]. But once a blanket implementation is also available for [T; N], Rust attempts to use it instead & then complains that it can't compare arrays of different lengths. I suppose this technically counts as a backwards-compatibility break.