Skip to main content

vector_core/crypto/gcm/
mod.rs

1//! AES-256-GCM with a 16-byte nonce and no associated data: the attachment cipher
2//! (0xChat-compatible). A stitched AES-NI/PCLMULQDQ engine where it has been measured
3//! to win, RustCrypto's `ctr` + `ghash` everywhere else; both produce the same bytes.
4
5#[cfg(target_arch = "x86_64")]
6mod x86;
7
8use aes::cipher::{BlockCipherEncrypt, KeyInit, KeyIvInit, StreamCipher, StreamCipherSeek};
9use aes::Aes256;
10use ghash::universal_hash::UniversalHash;
11use ghash::GHash;
12
13pub const TAG_LEN: usize = 16;
14
15// One per message, built and dropped on the stack: boxing the larger variant would cost
16// an allocation per seal.
17#[allow(clippy::large_enum_variant)]
18enum Engine {
19    #[cfg(target_arch = "x86_64")]
20    Stitched(x86::Gcm),
21    Generic { ctr: ctr::Ctr32BE<Aes256>, ghash: GHash, tag_mask: [u8; TAG_LEN] },
22}
23
24/// H = E_K(0^128), and the J0 a 16-byte nonce derives through GHASH (SP 800-38D 7.1).
25fn hash_key_and_j0(key: &[u8; 32], nonce: &[u8; 16]) -> (ghash::Block, ghash::Block) {
26    let cipher = Aes256::new(&(*key).into());
27    let mut h = ghash::Block::default();
28    cipher.encrypt_block(&mut h);
29    let mut j0_hash = GHash::new(&h);
30    j0_hash.update_padded(nonce);
31    let mut len_block = ghash::Block::default();
32    len_block[8..].copy_from_slice(&128u64.to_be_bytes());
33    j0_hash.update(&[len_block]);
34    (h, j0_hash.finalize())
35}
36
37/// One message's payload keystream, from any offset. It is CTR without GHASH, so it
38/// checks nothing: only for ciphertext whose tag was checked once already.
39pub struct Keystream(ctr::Ctr32BE<Aes256>);
40
41impl Keystream {
42    pub fn new(key: &[u8; 32], nonce: &[u8; 16]) -> Self {
43        let (_, j0) = hash_key_and_j0(key, nonce);
44        Self::from_j0(key, &j0)
45    }
46
47    fn from_j0(key: &[u8; 32], j0: &ghash::Block) -> Self {
48        Keystream(ctr::Ctr32BE::<Aes256>::new(&(*key).into(), j0))
49    }
50
51    /// Decrypt `buf`, the payload bytes that start `offset` bytes in. Fails only past the
52    /// longest message GCM allows.
53    pub fn apply_at(&mut self, offset: u64, buf: &mut [u8]) -> Result<(), PastTheEnd> {
54        // Keystream block 0 masks the tag; the payload starts at block 1.
55        let start = offset.checked_add(TAG_LEN as u64).ok_or(PastTheEnd)?;
56        self.0.try_seek(start).map_err(|_| PastTheEnd)?;
57        self.0.try_apply_keystream(buf).map_err(|_| PastTheEnd)
58    }
59}
60
61#[derive(Debug, PartialEq)]
62pub struct PastTheEnd;
63
64/// One GCM message fed in chunks. Every chunk but the last must be a multiple of 16
65/// bytes: GHASH may only pad the final block.
66pub struct Stream {
67    engine: Engine,
68    len: u64,
69    closed: bool,
70}
71
72impl Stream {
73    /// The stitched engine wherever it runs, key setup included: in `crypto_bench sweep`
74    /// it won every size from 0 bytes to 1 MiB against the generic one.
75    pub fn new(key: &[u8; 32], nonce: &[u8; 16]) -> Self {
76        #[cfg(target_arch = "x86_64")]
77        if x86::available() {
78            return Self::stitched(key, nonce);
79        }
80        Self::generic(key, nonce)
81    }
82
83    #[cfg(target_arch = "x86_64")]
84    fn stitched(key: &[u8; 32], nonce: &[u8; 16]) -> Self {
85        // SAFETY: callers establish `x86::instructions_present()`.
86        let gcm = unsafe { x86::Gcm::new(key, nonce) };
87        Stream { engine: Engine::Stitched(gcm), len: 0, closed: false }
88    }
89
90    fn generic(key: &[u8; 32], nonce: &[u8; 16]) -> Self {
91        let (h, j0) = hash_key_and_j0(key, nonce);
92
93        // Keystream block 0 masks the tag; the payload starts at block 1.
94        let mut ctr = ctr::Ctr32BE::<Aes256>::new(&(*key).into(), &j0);
95        let mut tag_mask = [0u8; TAG_LEN];
96        ctr.apply_keystream(&mut tag_mask);
97        Stream { engine: Engine::Generic { ctr, ghash: GHash::new(&h), tag_mask }, len: 0, closed: false }
98    }
99
100    fn account(&mut self, chunk: &[u8]) {
101        debug_assert!(!self.closed, "a chunk followed a partial one");
102        self.closed = !chunk.len().is_multiple_of(16);
103        self.len += chunk.len() as u64;
104    }
105
106    pub fn encrypt(&mut self, chunk: &mut [u8]) {
107        self.account(chunk);
108        match &mut self.engine {
109            // SAFETY: construction checked the instructions.
110            #[cfg(target_arch = "x86_64")]
111            Engine::Stitched(gcm) => unsafe { gcm.encrypt(chunk) },
112            Engine::Generic { ctr, ghash, .. } => {
113                ctr.apply_keystream(chunk);
114                ghash.update_padded(chunk);
115            }
116        }
117    }
118
119    pub fn decrypt(&mut self, chunk: &mut [u8]) {
120        self.account(chunk);
121        match &mut self.engine {
122            // SAFETY: construction checked the instructions.
123            #[cfg(target_arch = "x86_64")]
124            Engine::Stitched(gcm) => unsafe { gcm.decrypt(chunk) },
125            Engine::Generic { ctr, ghash, .. } => {
126                ghash.update_padded(chunk);
127                ctr.apply_keystream(chunk);
128            }
129        }
130    }
131
132    /// The tag over everything fed so far.
133    pub fn finish(self) -> [u8; TAG_LEN] {
134        match self.engine {
135            // SAFETY: construction checked the instructions.
136            #[cfg(target_arch = "x86_64")]
137            Engine::Stitched(gcm) => unsafe { gcm.finish(self.len) },
138            Engine::Generic { mut ghash, tag_mask, .. } => {
139                let mut lengths = ghash::Block::default();
140                lengths[8..].copy_from_slice(&(self.len * 8).to_be_bytes());
141                ghash.update(&[lengths]);
142                let mut tag = [0u8; TAG_LEN];
143                for (t, (s, m)) in tag.iter_mut().zip(ghash.finalize().iter().zip(tag_mask)) {
144                    *t = s ^ m;
145                }
146                tag
147            }
148        }
149    }
150}
151
152/// Seal `data` in place and return the tag.
153pub fn seal(key: &[u8; 32], nonce: &[u8; 16], data: &mut [u8]) -> [u8; TAG_LEN] {
154    let mut s = Stream::new(key, nonce);
155    s.encrypt(data);
156    s.finish()
157}
158
159/// The tag did not authenticate the ciphertext.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct TagMismatch;
162
163/// Open `data` in place. On a bad tag the buffer is wiped, so no unauthenticated
164/// plaintext survives the call.
165pub fn open(key: &[u8; 32], nonce: &[u8; 16], data: &mut [u8], tag: &[u8; TAG_LEN]) -> Result<(), TagMismatch> {
166    let mut s = Stream::new(key, nonce);
167    s.decrypt(data);
168    if tags_equal(&s.finish(), tag) {
169        Ok(())
170    } else {
171        super::wipe(data);
172        Err(TagMismatch)
173    }
174}
175
176/// Every byte compared, whatever the first difference.
177pub fn tags_equal(a: &[u8; TAG_LEN], b: &[u8; TAG_LEN]) -> bool {
178    let diff = a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y));
179    core::hint::black_box(diff) == 0
180}
181
182/// The engines with their choice forced, for measuring where the stitched one pays.
183#[doc(hidden)]
184pub mod bench {
185    use super::*;
186
187    /// Whether this CPU can run the stitched engine at all (VAES or not).
188    pub fn stitched_present() -> bool {
189        #[cfg(target_arch = "x86_64")]
190        {
191            x86::instructions_present()
192        }
193        #[cfg(not(target_arch = "x86_64"))]
194        {
195            false
196        }
197    }
198
199    /// Whether production picks the stitched engine on this CPU.
200    pub fn stitched_in_production() -> bool {
201        #[cfg(target_arch = "x86_64")]
202        {
203            x86::available()
204        }
205        #[cfg(not(target_arch = "x86_64"))]
206        {
207            false
208        }
209    }
210
211    /// A stream on the named engine ("stitched" or "generic"), or None if this CPU lacks it.
212    pub fn stream(engine: &str, key: &[u8; 32], nonce: &[u8; 16]) -> Option<Stream> {
213        match engine {
214            #[cfg(target_arch = "x86_64")]
215            "stitched" if x86::instructions_present() => Some(Stream::stitched(key, nonce)),
216            "generic" => Some(Stream::generic(key, nonce)),
217            _ => None,
218        }
219    }
220}
221
222#[cfg(test)]
223mod tests;