Skip to main content

aes/backends/fixslice/
word.rs

1use crate::{Block, backends::soft::MinWord};
2use cipher::{
3    Array,
4    array::ArraySize,
5    consts::{U1, U2, U4},
6};
7use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, Shl, Shr};
8
9/// Width-abstracted machine word holding one row of a bitsliced AES state.
10pub(crate) trait Word:
11    Sized
12    + Copy
13    + Default
14    + 'static
15    + BitAnd<Output = Self>
16    + BitAndAssign
17    + BitOr<Output = Self>
18    + BitOrAssign
19    + BitXor<Output = Self>
20    + BitXorAssign
21    + Not<Output = Self>
22    + Shl<u32, Output = Self>
23    + Shr<u32, Output = Self>
24{
25    /// Number of 128-bit blocks bitsliced together in one state.
26    type Blocks: ArraySize;
27
28    /// Width in bits of one row of the bitsliced state (4 for `u16`, 8 for
29    /// `u32`, 16 for `u64`).
30    const ROW_BITS: u32 = (size_of::<Self>() * 2) as u32;
31
32    /// Half of `ROW_BITS`.
33    const HALF_ROW: u32 = Self::ROW_BITS / 2;
34    /// Quarter of `ROW_BITS`.
35    const QUARTER_ROW: u32 = Self::ROW_BITS / 4;
36
37    /// Distance in bits to rotate a state row by `(rows, cols)` positions.
38    #[inline(always)]
39    fn ror_distance(rows: u32, cols: u32) -> u32 {
40        rows * Self::ROW_BITS + cols * Self::QUARTER_ROW
41    }
42
43    /// Rotate right by `n` bits.
44    fn ror(self, n: u32) -> Self;
45
46    /// Pack the same nibble across all 4 rows of the word.
47    fn uniform_row(b: u8) -> Self;
48
49    /// Place one nibble at each of the 4 row positions of the word (row 0 = LSB).
50    fn pack_rows(r0: u8, r1: u8, r2: u8, r3: u8) -> Self;
51
52    /// Replicate byte `b` across every byte of the word.
53    fn byte_repeat(b: u8) -> Self;
54
55    /// Pack `Self::Blocks` input blocks into a bitsliced 8-row state slice.
56    fn bitslice(output: &mut [Self], input: &Array<Block, Self::Blocks>);
57
58    /// Unpack a bitsliced 8-row state slice into `Self::Blocks` output blocks.
59    fn inv_bitslice(input: &[Self]) -> Array<Block, Self::Blocks>;
60
61    /// Broadcast the round key into all lanes.
62    fn broadcast(rkey: MinWord) -> Self;
63}
64
65impl Word for u16 {
66    type Blocks = U1;
67
68    #[inline(always)]
69    fn ror(self, n: u32) -> u16 {
70        self.rotate_right(n)
71    }
72
73    #[inline(always)]
74    fn uniform_row(b: u8) -> u16 {
75        (b as u16) * 0x1111
76    }
77
78    #[inline(always)]
79    fn pack_rows(r0: u8, r1: u8, r2: u8, r3: u8) -> u16 {
80        (r0 as u16) | ((r1 as u16) << 4) | ((r2 as u16) << 8) | ((r3 as u16) << 12)
81    }
82
83    #[inline(always)]
84    fn byte_repeat(b: u8) -> u16 {
85        (b as u16) * 0x0101
86    }
87
88    /// Bitslice one 128-bit input block into a 128-bit internal state.
89    fn bitslice(output: &mut [u16], input: &Array<Block, U1>) {
90        debug_assert_eq!(output.len(), 8);
91        let b = input[0].as_slice();
92
93        // Bitslicing is a bit index manipulation. 128 bits of data means each bit is positioned at
94        // a 7-bit index. AES data is a single 4x4 column-major matrix of bytes, so the index is
95        // initially ([c]olumn, [r]ow, [p]osition):
96        //     c1 c0 r1 r0 p2 p1 p0
97        //
98        // The desired bitsliced data groups first by bit position, then row, then column:
99        //     p2 p1 p0 r1 r0 c1 c0
100
101        fn read_reordered(input: &[u8]) -> u16 {
102            (u16::from(input[0x0])) | (u16::from(input[0x2]) << 8)
103        }
104
105        // Reorder each block's bytes on input
106        //     c1 c0 r1 r0 __ __ __ => c1 c0 r0 r1 __ __ __
107        // Reorder by relabeling (note the order of input)
108        //     c1 c0 r0 __ __ __ __ => r0 c1 c0 __ __ __ __
109        let mut t = [
110            read_reordered(&b[0x00..0x03]),
111            read_reordered(&b[0x04..0x07]),
112            read_reordered(&b[0x08..0x0b]),
113            read_reordered(&b[0x0c..0x0f]),
114            read_reordered(&b[0x01..0x04]),
115            read_reordered(&b[0x05..0x08]),
116            read_reordered(&b[0x09..0x0c]),
117            read_reordered(&b[0x0d..0x10]),
118        ];
119
120        bitslice_swaps(&mut t);
121
122        // Final bitsliced bit index, as desired:
123        //     p2 p1 p0 r1 r0 c1 c0
124        output[..8].copy_from_slice(&t);
125    }
126
127    /// Un-bitslice a 128-bit internal state into one 128-bit block.
128    fn inv_bitslice(input: &[u16]) -> Array<Block, U1> {
129        debug_assert_eq!(input.len(), 8);
130
131        // Unbitslicing is a bit index manipulation. 128 bits of data means each bit is positioned
132        // at a 7-bit index. AES data is a single 4x4 column-major matrix of bytes, so the desired
133        // index for the output is ([c]olumn, [r]ow, [p]osition):
134        //     c1 c0 r1 r0 p2 p1 p0
135        //
136        // The initially bitsliced data groups first by bit position, then row, then column:
137        //     p2 p1 p0 r1 r0 c1 c0
138
139        let mut t = [
140            input[0], input[1], input[2], input[3], input[4], input[5], input[6], input[7],
141        ];
142
143        bitslice_swaps(&mut t);
144
145        fn write_reordered(rows: u16, output: &mut [u8]) {
146            output[0x0] = rows as u8;
147            output[0x2] = (rows >> 8) as u8;
148        }
149
150        let mut output = Array::<Block, U1>::default();
151        // Reorder by relabeling (note the order of output)
152        //     r0 c1 c0 __ __ __ __ => c1 c0 r0 __ __ __ __
153        // Reorder each block's bytes on output
154        //     c1 c0 r0 r1 __ __ __ => c1 c0 r1 r0 __ __ __
155        write_reordered(t[0], &mut output[0][0x00..0x03]);
156        write_reordered(t[1], &mut output[0][0x04..0x07]);
157        write_reordered(t[2], &mut output[0][0x08..0x0b]);
158        write_reordered(t[3], &mut output[0][0x0c..0x0f]);
159        write_reordered(t[4], &mut output[0][0x01..0x04]);
160        write_reordered(t[5], &mut output[0][0x05..0x08]);
161        write_reordered(t[6], &mut output[0][0x09..0x0c]);
162        write_reordered(t[7], &mut output[0][0x0d..0x10]);
163
164        // Final AES bit index, as desired:
165        //     c1 c0 r1 r0 p2 p1 p0
166        output
167    }
168
169    fn broadcast(rkey: MinWord) -> u16 {
170        rkey
171    }
172}
173
174/// Expand an 8-bit row pattern to a 16-bit row pattern by doubling each bit:
175/// input bit `i` becomes output bits `2i` and `2i+1`. Branchless SWAR so LLVM
176/// folds it to a single 16-bit immediate when `b` is a constant.
177#[inline(always)]
178const fn double_bits_8_to_16(b: u8) -> u16 {
179    let x = b as u16;
180    // Spread the 8 bits of x to even positions 0,2,4,6,8,10,12,14.
181    let x = (x | (x << 4)) & 0x0f0f;
182    let x = (x | (x << 2)) & 0x3333;
183    let x = (x | (x << 1)) & 0x5555;
184    // Duplicate each spread bit to its adjacent odd position.
185    x | (x << 1)
186}
187
188/// Expand a 16-bit row pattern to a 32-bit row pattern by doubling each bit:
189/// input bit `i` becomes output bits `2i` and `2i+1`. Branchless SWAR so LLVM
190/// folds it to a single 32-bit immediate when `b` is a constant.
191#[inline(always)]
192const fn double_bits_16_to_32(b: u16) -> u32 {
193    let x = b as u32;
194    // Spread the 16 bits of x to even positions 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30.
195    let x = (x | (x << 8)) & 0x00FF00FF;
196    let x = (x | (x << 4)) & 0x0F0F0F0F;
197    let x = (x | (x << 2)) & 0x33333333;
198    let x = (x | (x << 1)) & 0x55555555;
199    // Duplicate each spread bit to its adjacent odd position.
200    x | (x << 1)
201}
202
203/// Expand a 16-bit row pattern to a 64-bit row pattern by quadrupling each bit:
204/// input bit `i` becomes output bits `4i`, `4i+1`, `4i+2`, and `4i+3`.
205/// Branchless SWAR so LLVM folds it to a single 64-bit immediate when `b` is
206/// a constant.
207#[inline(always)]
208const fn quad_bits_16_to_64(b: u16) -> u64 {
209    let x = b as u64;
210    // Spread the 16 bits of x to positions 0,4,8,12,16,20,24,28,32,36,40,44,48,52,56,60.
211    let x = (x | (x << 24)) & 0x000000FF000000FF;
212    let x = (x | (x << 12)) & 0x000F000F000F000F;
213    let x = (x | (x << 6)) & 0x0303030303030303;
214    let x = (x | (x << 3)) & 0x1111111111111111;
215    // Duplicate each spread bit to its adjacent odd position.
216    x | (x << 1) | (x << 2) | (x << 3)
217}
218
219impl Word for u32 {
220    type Blocks = U2;
221
222    #[inline(always)]
223    fn ror(self, n: u32) -> u32 {
224        self.rotate_right(n)
225    }
226
227    #[inline(always)]
228    fn uniform_row(b: u8) -> u32 {
229        double_bits_8_to_16(b) as u32 * 0x01010101
230    }
231
232    #[inline(always)]
233    fn pack_rows(r0: u8, r1: u8, r2: u8, r3: u8) -> u32 {
234        (double_bits_8_to_16(r0) as u32)
235            | ((double_bits_8_to_16(r1) as u32) << 8)
236            | ((double_bits_8_to_16(r2) as u32) << 16)
237            | ((double_bits_8_to_16(r3) as u32) << 24)
238    }
239
240    #[inline(always)]
241    fn byte_repeat(b: u8) -> u32 {
242        (b as u32) * 0x01010101
243    }
244
245    /// Bitslice two 128-bit input blocks into a 256-bit internal state.
246    fn bitslice(output: &mut [u32], input: &Array<Block, U2>) {
247        debug_assert_eq!(output.len(), 8);
248        let input0 = input[0].as_slice();
249        let input1 = input[1].as_slice();
250
251        // Bitslicing is a bit index manipulation. 256 bits of data means each bit is positioned at
252        // an 8-bit index. AES data is 2 blocks, each one a 4x4 column-major matrix of bytes, so the
253        // index is initially ([b]lock, [c]olumn, [r]ow, [p]osition):
254        //     b0 c1 c0 r1 r0 p2 p1 p0
255        //
256        // The desired bitsliced data groups first by bit position, then row, column, block:
257        //     p2 p1 p0 r1 r0 c1 c0 b0
258
259        // Interleave the columns on input (note the order of input)
260        //     b0 c1 c0 __ __ __ __ __ => c1 c0 b0 __ __ __ __ __
261        let mut t = [
262            u32::from_le_bytes(input0[0x00..0x04].try_into().unwrap()),
263            u32::from_le_bytes(input1[0x00..0x04].try_into().unwrap()),
264            u32::from_le_bytes(input0[0x04..0x08].try_into().unwrap()),
265            u32::from_le_bytes(input1[0x04..0x08].try_into().unwrap()),
266            u32::from_le_bytes(input0[0x08..0x0c].try_into().unwrap()),
267            u32::from_le_bytes(input1[0x08..0x0c].try_into().unwrap()),
268            u32::from_le_bytes(input0[0x0c..0x10].try_into().unwrap()),
269            u32::from_le_bytes(input1[0x0c..0x10].try_into().unwrap()),
270        ];
271
272        bitslice_swaps(&mut t);
273
274        // Final bitsliced bit index, as desired:
275        //     p2 p1 p0 r1 r0 c1 c0 b0
276        output[..8].copy_from_slice(&t);
277    }
278
279    /// Un-bitslice a 256-bit internal state into two 128-bit blocks.
280    fn inv_bitslice(input: &[u32]) -> Array<Block, U2> {
281        debug_assert_eq!(input.len(), 8);
282
283        // Unbitslicing is a bit index manipulation. 256 bits of data means each bit is positioned
284        // at an 8-bit index. AES data is 2 blocks, each one a 4x4 column-major matrix of bytes, so
285        // the desired index for the output is ([b]lock, [c]olumn, [r]ow, [p]osition):
286        //     b0 c1 c0 r1 r0 p2 p1 p0
287        //
288        // The initially bitsliced data groups first by bit position, then row, column, block:
289        //     p2 p1 p0 r1 r0 c1 c0 b0
290
291        let mut t = [
292            input[0], input[1], input[2], input[3], input[4], input[5], input[6], input[7],
293        ];
294
295        bitslice_swaps(&mut t);
296
297        let mut output = Array::<Block, U2>::default();
298        // De-interleave the columns on output (note the order of output)
299        //     c1 c0 b0 __ __ __ __ __ => b0 c1 c0 __ __ __ __ __
300        output[0][0x00..0x04].copy_from_slice(&t[0].to_le_bytes());
301        output[0][0x04..0x08].copy_from_slice(&t[2].to_le_bytes());
302        output[0][0x08..0x0c].copy_from_slice(&t[4].to_le_bytes());
303        output[0][0x0c..0x10].copy_from_slice(&t[6].to_le_bytes());
304        output[1][0x00..0x04].copy_from_slice(&t[1].to_le_bytes());
305        output[1][0x04..0x08].copy_from_slice(&t[3].to_le_bytes());
306        output[1][0x08..0x0c].copy_from_slice(&t[5].to_le_bytes());
307        output[1][0x0c..0x10].copy_from_slice(&t[7].to_le_bytes());
308
309        // Final AES bit index, as desired:
310        //     b0 c1 c0 r1 r0 p2 p1 p0
311        output
312    }
313
314    fn broadcast(rkey: MinWord) -> Self {
315        double_bits_16_to_32(rkey)
316    }
317}
318
319impl Word for u64 {
320    type Blocks = U4;
321
322    #[inline(always)]
323    fn ror(self, n: u32) -> u64 {
324        self.rotate_right(n)
325    }
326
327    #[inline(always)]
328    fn uniform_row(b: u8) -> u64 {
329        quad_bits_16_to_64(b as u16) * 0x0001_0001_0001_0001
330    }
331
332    #[inline(always)]
333    fn pack_rows(r0: u8, r1: u8, r2: u8, r3: u8) -> u64 {
334        quad_bits_16_to_64(r0 as u16)
335            | (quad_bits_16_to_64(r1 as u16) << 16)
336            | (quad_bits_16_to_64(r2 as u16) << 32)
337            | (quad_bits_16_to_64(r3 as u16) << 48)
338    }
339
340    #[inline(always)]
341    fn byte_repeat(b: u8) -> u64 {
342        (b as u64) * 0x0101010101010101
343    }
344
345    /// Bitslice four 128-bit input blocks into a 512-bit internal state.
346    fn bitslice(output: &mut [u64], input: &Array<Block, U4>) {
347        debug_assert_eq!(output.len(), 8);
348
349        // Bitslicing is a bit index manipulation. 512 bits of data means each bit is positioned at
350        // a 9-bit index. AES data is 4 blocks, each one a 4x4 column-major matrix of bytes, so the
351        // index is initially ([b]lock, [c]olumn, [r]ow, [p]osition):
352        //     b1 b0 c1 c0 r1 r0 p2 p1 p0
353        //
354        // The desired bitsliced data groups first by bit position, then row, column, block:
355        //     p2 p1 p0 r1 r0 c1 c0 b1 b0
356
357        #[rustfmt::skip]
358        fn read_reordered(input: &[u8]) -> u64 {
359            (u64::from(input[0x0])        ) |
360            (u64::from(input[0x1]) << 0x10) |
361            (u64::from(input[0x2]) << 0x20) |
362            (u64::from(input[0x3]) << 0x30) |
363            (u64::from(input[0x8]) << 0x08) |
364            (u64::from(input[0x9]) << 0x18) |
365            (u64::from(input[0xa]) << 0x28) |
366            (u64::from(input[0xb]) << 0x38)
367        }
368
369        // Reorder each block's bytes on input
370        //     __ __ c1 c0 r1 r0 __ __ __ => __ __ c0 r1 r0 c1 __ __ __
371        // Reorder by relabeling (note the order of input)
372        //     b1 b0 c0 __ __ __ __ __ __ => c0 b1 b0 __ __ __ __ __ __
373        let mut t = [
374            read_reordered(&input[0][0x00..0x0c]),
375            read_reordered(&input[1][0x00..0x0c]),
376            read_reordered(&input[2][0x00..0x0c]),
377            read_reordered(&input[3][0x00..0x0c]),
378            read_reordered(&input[0][0x04..0x10]),
379            read_reordered(&input[1][0x04..0x10]),
380            read_reordered(&input[2][0x04..0x10]),
381            read_reordered(&input[3][0x04..0x10]),
382        ];
383
384        bitslice_swaps(&mut t);
385
386        // Final bitsliced bit index, as desired:
387        //     p2 p1 p0 r1 r0 c1 c0 b1 b0
388        output[..8].copy_from_slice(&t);
389    }
390
391    /// Un-bitslice a 512-bit internal state into four 128-bit blocks.
392    fn inv_bitslice(input: &[u64]) -> Array<Block, U4> {
393        debug_assert_eq!(input.len(), 8);
394
395        // Unbitslicing is a bit index manipulation. 512 bits of data means each bit is positioned
396        // at a 9-bit index. AES data is 4 blocks, each one a 4x4 column-major matrix of bytes, so
397        // the desired index for the output is ([b]lock, [c]olumn, [r]ow, [p]osition):
398        //     b1 b0 c1 c0 r1 r0 p2 p1 p0
399        //
400        // The initially bitsliced data groups first by bit position, then row, column, block:
401        //     p2 p1 p0 r1 r0 c1 c0 b1 b0
402
403        let mut t = [
404            input[0], input[1], input[2], input[3], input[4], input[5], input[6], input[7],
405        ];
406
407        bitslice_swaps(&mut t);
408
409        #[rustfmt::skip]
410        fn write_reordered(columns: u64, output: &mut [u8]) {
411            output[0x0] = (columns        ) as u8;
412            output[0x1] = (columns >> 0x10) as u8;
413            output[0x2] = (columns >> 0x20) as u8;
414            output[0x3] = (columns >> 0x30) as u8;
415            output[0x8] = (columns >> 0x08) as u8;
416            output[0x9] = (columns >> 0x18) as u8;
417            output[0xa] = (columns >> 0x28) as u8;
418            output[0xb] = (columns >> 0x38) as u8;
419        }
420
421        let mut output = Array::<Block, U4>::default();
422        // Reorder by relabeling (note the order of output)
423        //     c0 b1 b0 __ __ __ __ __ __ => b1 b0 c0 __ __ __ __ __ __
424        // Reorder each block's bytes on output
425        //     __ __ c0 r1 r0 c1 __ __ __ => __ __ c1 c0 r1 r0 __ __ __
426        write_reordered(t[0], &mut output[0][0x00..0x0c]);
427        write_reordered(t[4], &mut output[0][0x04..0x10]);
428        write_reordered(t[1], &mut output[1][0x00..0x0c]);
429        write_reordered(t[5], &mut output[1][0x04..0x10]);
430        write_reordered(t[2], &mut output[2][0x00..0x0c]);
431        write_reordered(t[6], &mut output[2][0x04..0x10]);
432        write_reordered(t[3], &mut output[3][0x00..0x0c]);
433        write_reordered(t[7], &mut output[3][0x04..0x10]);
434
435        // Final AES bit index, as desired:
436        //     b1 b0 c1 c0 r1 r0 p2 p1 p0
437        output
438    }
439
440    fn broadcast(rkey: MinWord) -> Self {
441        quad_bits_16_to_64(rkey)
442    }
443}
444
445/// Width-generic delta-swap pipeline shared by `bitslice` and `inv_bitslice`
446/// across every `Word` impl. The same three-pass sequence inverts itself, so
447/// `bitslice` and `inv_bitslice` invoke it identically.
448///
449/// The diagrams below describe the `u32` case (8-bit rows); for `u64` each
450/// bit position widens by one, but the swap structure is unchanged.
451#[inline(always)]
452fn bitslice_swaps<W: Word>(t: &mut [W; 8]) {
453    use super::utils::delta_swap_2;
454    let [t0, t1, t2, t3, t4, t5, t6, t7] = t;
455
456    // Bit Index Swap 5 <-> 0:
457    //     __ __ b0 __ __ __ __ p0 => __ __ p0 __ __ __ __ b0
458    let m0 = W::byte_repeat(0x55);
459    delta_swap_2(t1, t0, 1, m0);
460    delta_swap_2(t3, t2, 1, m0);
461    delta_swap_2(t5, t4, 1, m0);
462    delta_swap_2(t7, t6, 1, m0);
463
464    // Bit Index Swap 6 <-> 1:
465    //     __ c0 __ __ __ __ p1 __ => __ p1 __ __ __ __ c0 __
466    let m1 = W::byte_repeat(0x33);
467    delta_swap_2(t2, t0, 2, m1);
468    delta_swap_2(t3, t1, 2, m1);
469    delta_swap_2(t6, t4, 2, m1);
470    delta_swap_2(t7, t5, 2, m1);
471
472    // Bit Index Swap 7 <-> 2:
473    //     c1 __ __ __ __ p2 __ __ => p2 __ __ __ __ c1 __ __
474    let m2 = W::byte_repeat(0x0f);
475    delta_swap_2(t4, t0, 4, m2);
476    delta_swap_2(t5, t1, 4, m2);
477    delta_swap_2(t6, t2, 4, m2);
478    delta_swap_2(t7, t3, 4, m2);
479}