interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-crypto / src / polyval.rs

168 lines · 5138 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Pure-Rust, allocation-free POLYVAL universal hash implementation conforming to RFC 8452.
17//!
18//! Evaluates polynomial authentication tags over GF(2^128) modulo
19//! x^128 + x^127 + x^126 + x^121 + 1.
20
21/// 16-byte POLYVAL block.
22pub type Block = [u8; 16];
23
24/// POLYVAL state accumulator.
25#[derive(Clone, Default)]
26pub struct Polyval {
27 key: Block,
28 accumulator: Block,
29}
30
31impl core::fmt::Debug for Polyval {
32 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
33 write!(f, "Polyval([REDACTED])")
34 }
35}
36
37impl Drop for Polyval {
38 fn drop(&mut self) {
39 for b in &mut self.key {
40 unsafe { core::ptr::write_volatile(b, 0) };
41 }
42 for b in &mut self.accumulator {
43 unsafe { core::ptr::write_volatile(b, 0) };
44 }
45 }
46}
47
48/// Constant field element x^-1: byte 15 = 0xe1, bytes 0..15 = 0x00.
49const X_INV_BYTE_15: u8 = 0xe1;
50
51/// Multiply polynomial V by x^-1 modulo x^128 + x^127 + x^126 + x^121 + 1.
52#[inline(always)]
53fn div_x(v: &mut Block) {
54 let lsb = v[0] & 1;
55
56 // Shift 128-bit array right by 1 bit (little-endian: bit 0 is LSB of byte 0).
57 let mut carry = 0u8;
58 for byte in v.iter_mut().rev() {
59 let next_carry = *byte & 1;
60 *byte = (*byte >> 1) | (carry << 7);
61 carry = next_carry;
62 }
63
64 // Branch-free reduction: mask is 0xff when lsb == 1, 0x00 when lsb == 0.
65 v[15] ^= X_INV_BYTE_15 & 0u8.wrapping_sub(core::hint::black_box(lsb));
66}
67
68/// Compute dot(a, b) = a * b * x^-128 mod P(x) per RFC 8452 Section 3.
69///
70/// Constant-time: always 128 steps, no branch or memory address depends on `a` or `b`.
71pub fn dot(a: &Block, b: &Block) -> Block {
72 let mut v = [0u8; 16];
73
74 for i in 0..128 {
75 let byte_idx = i / 8;
76 let bit_idx = i % 8;
77 let bit = (a[byte_idx] >> bit_idx) & 1;
78
79 // Branch-free conditional add: mask is 0xff when bit == 1, else 0x00.
80 // `black_box` hides that `bit` is 0 or 1, so LLVM cannot turn the mask
81 // back into a branch (it did so without it; seen in AArch64 disassembly).
82 let mask = 0u8.wrapping_sub(core::hint::black_box(bit));
83 for j in 0..16 {
84 v[j] ^= b[j] & mask;
85 }
86
87 div_x(&mut v);
88 }
89
90 v
91}
92
93impl Polyval {
94 /// Initialize POLYVAL with a 16-byte authentication key H.
95 pub fn new(key: &Block) -> Self {
96 Self {
97 key: *key,
98 accumulator: [0u8; 16],
99 }
100 }
101
102 /// Reset accumulator to zero.
103 pub fn reset(&mut self) {
104 self.accumulator = [0u8; 16];
105 }
106
107 /// Process a single 16-byte block: S_j = dot(S_{j-1} ^ X_j, H).
108 pub fn update_block(&mut self, block: &Block) {
109 for (acc, b) in self.accumulator.iter_mut().zip(block.iter()) {
110 *acc ^= b;
111 }
112 self.accumulator = dot(&self.accumulator, &self.key);
113 }
114
115 /// Process arbitrary slice of padded 16-byte blocks.
116 pub fn update(&mut self, data: &[u8]) {
117 assert!(
118 data.len().is_multiple_of(16),
119 "POLYVAL input must be 16-byte aligned"
120 );
121 let (chunks, _) = data.as_chunks::<16>();
122 for chunk in chunks {
123 self.update_block(chunk);
124 }
125 }
126
127 /// Finalize and return current 16-byte accumulator S_s.
128 pub fn finalize(self) -> Block {
129 self.accumulator
130 }
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136
137 fn hex_to_block(hex: &str) -> Block {
138 assert_eq!(hex.len(), 32);
139 let mut block = [0u8; 16];
140 for i in 0..16 {
141 block[i] = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap();
142 }
143 block
144 }
145
146 #[test]
147 fn test_polyval_rfc8452_section_7_dot() {
148 let a = hex_to_block("66e94bd4ef8a2c3b884cfa59ca342b2e");
149 let b = hex_to_block("ff000000000000000000000000000000");
150 let expected = hex_to_block("ebe563401e7e91ea3ad6426b8140c394");
151
152 let res = dot(&a, &b);
153 assert_eq!(res, expected);
154 }
155
156 #[test]
157 fn test_polyval_rfc8452_appendix_a_worked_example() {
158 let h = hex_to_block("25629347589242761d31f826ba4b757b");
159 let x1 = hex_to_block("4f4f95668c83dfb6401762bb2d01a262");
160 let x2 = hex_to_block("d1a24ddd2721d006bbe45f20d3c9f362");
161 let expected = hex_to_block("f7a3b47b846119fae5b7866cf5e5b77e");
162
163 let mut poly = Polyval::new(&h);
164 poly.update_block(&x1);
165 poly.update_block(&x2);
166 assert_eq!(poly.finalize(), expected);
167 }
168}