Skip to content

Commit bcd83cf

Browse files
committed
add ct_lsb_prop_u16
1 parent 0aca085 commit bcd83cf

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

tlslite/utils/constanttime.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ def ct_lt_u32(val_a, val_b):
2323

2424
return (val_a^((val_a^val_b)|(((val_a-val_b)&0xffffffff)^val_b)))>>31
2525

26+
2627
def ct_gt_u32(val_a, val_b):
2728
"""
2829
Return 1 if val_a > val_b, 0 otherwise. Constant time.
@@ -35,6 +36,7 @@ def ct_gt_u32(val_a, val_b):
3536
"""
3637
return ct_lt_u32(val_b, val_a)
3738

39+
3840
def ct_le_u32(val_a, val_b):
3941
"""
4042
Return 1 if val_a <= val_b, 0 otherwise. Constant time.
@@ -47,14 +49,26 @@ def ct_le_u32(val_a, val_b):
4749
"""
4850
return 1 ^ ct_gt_u32(val_a, val_b)
4951

52+
5053
def ct_lsb_prop_u8(val):
51-
"""Propagate LSB to all 8 bits of the returned byte. Constant time."""
54+
"""Propagate LSB to all 8 bits of the returned int. Constant time."""
55+
val &= 0x01
56+
val |= val << 1
57+
val |= val << 2
58+
val |= val << 4
59+
return val
60+
61+
62+
def ct_lsb_prop_u16(val):
63+
"""Propagate LSB to all 16 bits of the returned int. Constant time."""
5264
val &= 0x01
5365
val |= val << 1
5466
val |= val << 2
5567
val |= val << 4
68+
val |= val << 8
5669
return val
5770

71+
5872
def ct_isnonzero_u32(val):
5973
"""
6074
Returns 1 if val is != 0, 0 otherwise. Constant time.
@@ -66,6 +80,7 @@ def ct_isnonzero_u32(val):
6680
val &= 0xffffffff
6781
return (val|(-val&0xffffffff)) >> 31
6882

83+
6984
def ct_neq_u32(val_a, val_b):
7085
"""
7186
Return 1 if val_a != val_b, 0 otherwise. Constant time.

unit_tests/test_tlslite_utils_constanttime.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from tlslite.utils.constanttime import ct_lt_u32, ct_gt_u32, ct_le_u32, \
1313
ct_lsb_prop_u8, ct_isnonzero_u32, ct_neq_u32, ct_eq_u32, \
14-
ct_check_cbc_mac_and_pad, ct_compare_digest
14+
ct_check_cbc_mac_and_pad, ct_compare_digest, ct_lsb_prop_u16
1515

1616
from hypothesis import given, example
1717
import hypothesis.strategies as st
@@ -80,6 +80,14 @@ def test_ct_lsb_prop_u8(self, i):
8080
self.assertEqual(((i & 0x1) == 1), (ct_lsb_prop_u8(i) == 0xff))
8181
self.assertEqual(((i & 0x1) == 0), (ct_lsb_prop_u8(i) == 0x00))
8282

83+
@given(i=st.integers(0, 2**16-1))
84+
@example(i=0)
85+
@example(i=255)
86+
@example(i=2**16-1)
87+
def test_ct_lsb_prop_u16(self, i):
88+
self.assertEqual(((i & 0x1) == 1), (ct_lsb_prop_u16(i) == 0xffff))
89+
self.assertEqual(((i & 0x1) == 0), (ct_lsb_prop_u16(i) == 0x0000))
90+
8391
@given(i=st.integers(0,2**32 - 1))
8492
@example(i=0)
8593
def test_ct_isnonzero_u32(self, i):

0 commit comments

Comments
 (0)