vector_core/crypto/gcm/
mod.rs1#[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#[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
24fn 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
37pub 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 pub fn apply_at(&mut self, offset: u64, buf: &mut [u8]) -> Result<(), PastTheEnd> {
54 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
64pub struct Stream {
67 engine: Engine,
68 len: u64,
69 closed: bool,
70}
71
72impl Stream {
73 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 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 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 #[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 #[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 pub fn finish(self) -> [u8; TAG_LEN] {
134 match self.engine {
135 #[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
152pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct TagMismatch;
162
163pub 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
176pub 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#[doc(hidden)]
184pub mod bench {
185 use super::*;
186
187 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 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 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;