hare

The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

commit e663fb3eb78feb1ad8eadb3c0ba06227a3f742dd
parent a47cbb44ba562c81817dfcc21fac6fd3d112ef3c
Author: Thomas Bracht Laumann Jespersen <t@laumann.xyz>
Date:   Mon, 29 Nov 2021 09:13:30 +0100

crypto/math: Add constant-time byte slice comparison

Signed-off-by: Thomas Bracht Laumann Jespersen <t@laumann.xyz>

Diffstat:
Mcrypto/math/bits.ha | 21+++++++++++++++++++++
1 file changed, 21 insertions(+), 0 deletions(-)

diff --git a/crypto/math/bits.ha b/crypto/math/bits.ha @@ -53,3 +53,24 @@ export fn xor(dest: []u8, a: []u8, b: []u8) void = { dest[i] = a[i] ^ b[i]; }; }; + +// Compare two byte slices in constant time. +// +// Returns 1 if the two slices have the same contents, 0 otherwise. +export fn cmpslice(x: []u8, y: []u8) int = { + assert(len(x) == len(y), "slices must have the same length"); + let v: u8 = 0; + for (let i = 0z; i < len(x); i += 1) { + v = x[i] ^ y[i]; + }; + return cmpu8(v, 0); +}; + +@test fn cmpslice() void = { + assert(cmpslice([], []) == 1); + assert(cmpslice([0], [0]) == 1); +}; + +// Compare two bytes in constant time. Returns 1 if the bytes are the same +// value, 0 otherwise. +export fn cmpu8(x: u8, y: u8) int = ((((x ^ y) : u32) - 1) >> 31) : int;