cryprot-core 0.3.2

Core primitives for cryptographic protocol implementations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! A 128-bit [`Block`] type.
//!
//! Operations on [`Block`]s will use SIMD instructions where possible.
use std::{
    fmt,
    ops::{Add, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, Shl, Shr},
};

use aes::cipher::{self, array::sizes};
use bytemuck::{Pod, Zeroable};
use rand::{Rng, distr::StandardUniform, prelude::Distribution};
use serde::{Deserialize, Serialize};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use thiserror::Error;
use wide::u8x16;

use crate::random_oracle::{self, RandomOracle};

pub mod gf128;

/// A 128-bit block. Uses SIMD operations where available.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, Pod, Zeroable)]
#[repr(transparent)]
pub struct Block(u8x16);

impl Block {
    /// All bits set to 0.
    pub const ZERO: Self = Self(u8x16::ZERO);
    /// All bits set to 1.
    pub const ONES: Self = Self(u8x16::MAX);
    /// Lsb set to 1, all others zero.
    pub const ONE: Self = Self::new(1_u128.to_ne_bytes());
    /// Mask to mask off the LSB of a Block.
    /// ```rust
    /// # use cryprot_core::Block;
    /// let b = Block::ONES;
    /// let masked = b & Block::MASK_LSB;
    /// assert_eq!(masked, Block::ONES << 1)
    /// ```
    pub const MASK_LSB: Self = Self::pack(u64::MAX << 1, u64::MAX);

    /// 16 bytes in a Block.
    pub const BYTES: usize = 16;
    /// 128 bits in a block.
    pub const BITS: usize = 128;

    /// Create a new block from bytes.
    #[inline]
    pub const fn new(bytes: [u8; 16]) -> Self {
        Self(u8x16::new(bytes))
    }

    /// Create a block with all bytes set to `byte`.
    #[inline]
    pub const fn splat(byte: u8) -> Self {
        Self::new([byte; 16])
    }

    /// Pack two `u64` into a Block. Usable in const context.
    ///
    /// In non-const contexts, using `Block::from([low, high])` is likely
    /// faster.
    #[inline]
    pub const fn pack(low: u64, high: u64) -> Self {
        let mut bytes = [0; 16];
        let low = low.to_ne_bytes();
        let mut i = 0;
        while i < low.len() {
            bytes[i] = low[i];
            i += 1;
        }

        let high = high.to_ne_bytes();
        let mut i = 0;
        while i < high.len() {
            bytes[i + 8] = high[i];
            i += 1;
        }

        Self::new(bytes)
    }

    /// Bytes of the block.
    #[inline]
    pub fn as_bytes(&self) -> &[u8; 16] {
        self.0.as_array()
    }

    /// Mutable bytes of the block.
    #[inline]
    pub fn as_mut_bytes(&mut self) -> &mut [u8; 16] {
        self.0.as_mut_array()
    }

    /// Hash the block with a [`random_oracle`].
    #[inline]
    pub fn ro_hash(&self) -> random_oracle::Hash {
        let mut ro = RandomOracle::new();
        ro.update(self.as_bytes());
        ro.finalize()
    }

    ///  Create a block from 128 [`Choice`]s.
    ///
    /// # Panics
    /// If choices.len() != 128
    #[inline]
    pub fn from_choices(choices: &[Choice]) -> Self {
        assert_eq!(128, choices.len(), "choices.len() must be 128");
        let mut bytes = [0_u8; 16];
        for (chunk, byte) in choices.chunks_exact(8).zip(&mut bytes) {
            for (i, choice) in chunk.iter().enumerate() {
                *byte ^= choice.unwrap_u8() << i;
            }
        }
        Self::new(bytes)
    }

    /// Low 64 bits of the block.
    #[inline]
    pub fn low(&self) -> u64 {
        u64::from_ne_bytes(self.as_bytes()[..8].try_into().expect("correct len"))
    }

    /// High 64 bits of the block.
    #[inline]
    pub fn high(&self) -> u64 {
        u64::from_ne_bytes(self.as_bytes()[8..].try_into().expect("correct len"))
    }

    /// Least significant bit of the block
    #[inline]
    pub fn lsb(&self) -> bool {
        *self & Block::ONE == Block::ONE
    }

    /// Iterator over bits of the Block.
    #[inline]
    pub fn bits(&self) -> impl Iterator<Item = bool> {
        struct BitIter {
            blk: Block,
            idx: usize,
        }
        impl Iterator for BitIter {
            type Item = bool;

            #[inline]
            fn next(&mut self) -> Option<Self::Item> {
                if self.idx < Block::BITS {
                    self.idx += 1;
                    let bit = (self.blk >> (self.idx - 1)) & Block::ONE != Block::ZERO;
                    Some(bit)
                } else {
                    None
                }
            }
        }
        BitIter { blk: *self, idx: 0 }
    }
}

// Implement standard operators for more ergonomic usage
impl BitAnd for Block {
    type Output = Self;

    #[inline]
    fn bitand(self, rhs: Self) -> Self {
        Self(self.0 & rhs.0)
    }
}

impl BitAndAssign for Block {
    #[inline]
    fn bitand_assign(&mut self, rhs: Self) {
        *self = *self & rhs;
    }
}

impl BitOr for Block {
    type Output = Self;

    #[inline]
    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

impl BitOrAssign for Block {
    #[inline]
    fn bitor_assign(&mut self, rhs: Self) {
        *self = *self | rhs;
    }
}

impl BitXor for Block {
    type Output = Self;

    #[inline]
    fn bitxor(self, rhs: Self) -> Self {
        Self(self.0 ^ rhs.0)
    }
}

impl BitXorAssign for Block {
    #[inline]
    fn bitxor_assign(&mut self, rhs: Self) {
        *self = *self ^ rhs;
    }
}

impl<Rhs> Shl<Rhs> for Block
where
    u128: Shl<Rhs, Output = u128>,
{
    type Output = Block;

    #[inline]
    fn shl(self, rhs: Rhs) -> Self::Output {
        Self::from(u128::from(self) << rhs)
    }
}

impl<Rhs> Shr<Rhs> for Block
where
    u128: Shr<Rhs, Output = u128>,
{
    type Output = Block;

    #[inline]
    fn shr(self, rhs: Rhs) -> Self::Output {
        Self::from(u128::from(self) >> rhs)
    }
}

impl Not for Block {
    type Output = Self;

    #[inline]
    fn not(self) -> Self {
        Self(!self.0)
    }
}

impl PartialEq for Block {
    fn eq(&self, other: &Self) -> bool {
        let a: u128 = (*self).into();
        let b: u128 = (*other).into();
        a.ct_eq(&b).into()
    }
}

impl Eq for Block {}

impl Distribution<Block> for StandardUniform {
    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Block {
        let mut bytes = [0; 16];
        rng.fill_bytes(&mut bytes);
        Block::new(bytes)
    }
}

impl AsRef<[u8]> for Block {
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl AsMut<[u8]> for Block {
    #[inline]
    fn as_mut(&mut self) -> &mut [u8] {
        self.as_mut_bytes()
    }
}

impl From<Block> for cipher::Array<u8, sizes::U16> {
    #[inline]
    fn from(value: Block) -> Self {
        Self(*value.as_bytes())
    }
}

impl From<cipher::Array<u8, sizes::U16>> for Block {
    #[inline]
    fn from(value: cipher::Array<u8, sizes::U16>) -> Self {
        Self::new(value.0)
    }
}

impl From<[u64; 2]> for Block {
    #[inline]
    fn from(value: [u64; 2]) -> Self {
        bytemuck::cast(value)
    }
}

impl From<Block> for [u64; 2] {
    #[inline]
    fn from(value: Block) -> Self {
        bytemuck::cast(value)
    }
}

impl From<Block> for u128 {
    #[inline]
    fn from(value: Block) -> Self {
        // todo correct endianness?
        u128::from_ne_bytes(*value.as_bytes())
    }
}

impl From<&Block> for u128 {
    #[inline]
    fn from(value: &Block) -> Self {
        // todo correct endianness?
        u128::from_ne_bytes(*value.as_bytes())
    }
}

impl From<usize> for Block {
    fn from(value: usize) -> Self {
        (value as u128).into()
    }
}

impl From<u128> for Block {
    #[inline]
    fn from(value: u128) -> Self {
        Self::new(value.to_ne_bytes())
    }
}

impl From<&u128> for Block {
    #[inline]
    fn from(value: &u128) -> Self {
        Self::new(value.to_ne_bytes())
    }
}

#[derive(Debug, Error)]
#[error("slice must have length of 16")]
pub struct WrongLength;

impl TryFrom<&[u8]> for Block {
    type Error = WrongLength;

    #[inline]
    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        let arr = value.try_into().map_err(|_| WrongLength)?;
        Ok(Self::new(arr))
    }
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
mod from_arch_impls {
    #[cfg(target_arch = "x86")]
    use std::arch::x86::*;
    #[cfg(target_arch = "x86_64")]
    use std::arch::x86_64::*;

    use super::Block;

    impl From<__m128i> for Block {
        #[inline]
        fn from(value: __m128i) -> Self {
            bytemuck::must_cast(value)
        }
    }

    impl From<&__m128i> for Block {
        #[inline]
        fn from(value: &__m128i) -> Self {
            bytemuck::must_cast(*value)
        }
    }

    impl From<Block> for __m128i {
        #[inline]
        fn from(value: Block) -> Self {
            bytemuck::must_cast(value)
        }
    }

    impl From<&Block> for __m128i {
        #[inline]
        fn from(value: &Block) -> Self {
            bytemuck::must_cast(*value)
        }
    }
}

impl ConditionallySelectable for Block {
    #[inline]
    // adapted from https://github.com/dalek-cryptography/subtle/blob/369e7463e85921377a5f2df80aabcbbc6d57a930/src/lib.rs#L510-L517
    fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
        // if choice = 0, mask = (-0) = 0000...0000
        // if choice = 1, mask = (-1) = 1111...1111
        let mask = Block::new((-(choice.unwrap_u8() as i128)).to_le_bytes());
        *a ^ (mask & (*a ^ *b))
    }
}

impl Add for Block {
    type Output = Block;

    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        // todo is this a sensible implementation?
        let a: u128 = self.into();
        let b: u128 = rhs.into();
        Self::from(a.wrapping_add(b))
    }
}

impl fmt::Binary for Block {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Binary::fmt(&u128::from(*self), f)
    }
}

#[cfg(feature = "num-traits")]
impl num_traits::Zero for Block {
    fn zero() -> Self {
        Self::ZERO
    }

    fn is_zero(&self) -> bool {
        *self == Self::ZERO
    }
}

#[cfg(test)]
mod tests {
    use subtle::{Choice, ConditionallySelectable};

    use crate::Block;

    #[test]
    fn test_block_cond_select() {
        let choice = Choice::from(0);
        assert_eq!(
            Block::ZERO,
            Block::conditional_select(&Block::ZERO, &Block::ONES, choice)
        );
        let choice = Choice::from(1);
        assert_eq!(
            Block::ONES,
            Block::conditional_select(&Block::ZERO, &Block::ONES, choice)
        );
    }

    #[test]
    fn test_block_low_high() {
        let b = Block::from(1_u128);
        assert_eq!(1, b.low());
        assert_eq!(0, b.high());
    }

    #[test]
    fn test_from_into_u64_arr() {
        let b = Block::from([42, 65]);
        assert_eq!(42, b.low());
        assert_eq!(65, b.high());
        assert_eq!([42, 65], <[u64; 2]>::from(b));
    }

    #[test]
    fn test_pack() {
        let b = Block::pack(42, 123);
        assert_eq!(42, b.low());
        assert_eq!(123, b.high());
    }

    #[test]
    fn test_mask_lsb() {
        assert_eq!(Block::ONES ^ Block::ONE, Block::MASK_LSB);
    }

    #[test]
    fn test_bits() {
        let b: Block = 0b101_u128.into();
        let mut iter = b.bits();
        assert_eq!(Some(true), iter.next());
        assert_eq!(Some(false), iter.next());
        assert_eq!(Some(true), iter.next());
        for rest in iter {
            assert_eq!(false, rest);
        }
    }

    #[test]
    fn test_from_choices() {
        let mut choices = vec![Choice::from(0); 128];
        choices[2] = Choice::from(1);
        choices[16] = Choice::from(1);
        let blk = Block::from_choices(&choices);
        assert_eq!(Block::from(1_u128 << 2 | 1_u128 << 16), blk);
    }
}