aes/lib.rs
1//! Pure Rust implementation of the [Advanced Encryption Standard][AES]
2//! (AES, a.k.a. Rijndael).
3//!
4//! # ⚠️ Security Warning: Hazmat!
5//!
6//! This crate implements only the low-level block cipher function, and is intended
7//! for use for implementing higher-level constructions *only*. It is NOT
8//! intended for direct use in applications.
9//!
10//! USE AT YOUR OWN RISK!
11//!
12//! # Supported backends
13//! This crate provides multiple backends including a portable pure Rust
14//! backend as well as ones based on CPU intrinsics.
15//!
16//! By default, it performs runtime detection of CPU intrinsics and uses them
17//! if they are available.
18//!
19//! ## "soft" portable backend
20//! As a baseline implementation, this crate provides a constant-time pure Rust
21//! implementation based on [fixslicing], a more advanced form of bitslicing
22//! implemented entirely in terms of bitwise arithmetic with no use of any
23//! lookup tables or data-dependent branches.
24//!
25//! Enabling the `aes_compact` configuration flag will reduce the code size of this
26//! backend at the cost of decreased performance (using a modified form of
27//! the fixslicing technique called "semi-fixslicing").
28//!
29//! ## ARMv8 intrinsics (Rust 1.61+)
30//! On `aarch64` targets including `aarch64-apple-darwin` (Apple M1) and Linux
31//! targets such as `aarch64-unknown-linux-gnu` and `aarch64-unknown-linux-musl`,
32//! support for using AES intrinsics provided by the ARMv8 Cryptography Extensions.
33//!
34//! On Linux and macOS, support for ARMv8 AES intrinsics is autodetected at
35//! runtime. On other platforms the `aes` target feature must be enabled via
36//! RUSTFLAGS.
37//!
38//! ## `x86`/`x86_64` intrinsics (AES-NI and VAES)
39//! By default this crate uses runtime detection on `i686`/`x86_64` targets
40//! in order to determine if AES-NI and VAES are available, and if they are
41//! not, it will fallback to using a constant-time software implementation.
42//!
43//! Passing `RUSTFLAGS=-Ctarget-feature=+aes,+ssse3` explicitly at
44//! compile-time will override runtime detection and ensure that AES-NI is
45//! used or passing `RUSTFLAGS=-Ctarget-feature=+aes,+avx512f,+ssse3,+vaes`
46//! will ensure that AESNI and VAES are always used.
47//!
48//! Programs built in this manner will crash with an illegal instruction on
49//! CPUs which do not have AES-NI and VAES enabled.
50//!
51//! Note: runtime detection is not possible on SGX targets. Please use the
52//! aforementioned `RUSTFLAGS` to leverage AES-NI and VAES on these targets.
53//!
54//! # Examples
55//! ```
56//! use aes::Aes128;
57//! use aes::cipher::{Array, BlockCipherEncrypt, BlockCipherDecrypt, KeyInit};
58//!
59//! let key = Array::from([0u8; 16]);
60//! let mut block = Array::from([42u8; 16]);
61//!
62//! // Initialize cipher
63//! let cipher = Aes128::new(&key);
64//!
65//! let block_copy = block;
66//!
67//! // Encrypt block in-place
68//! cipher.encrypt_block(&mut block);
69//!
70//! // And decrypt it back
71//! cipher.decrypt_block(&mut block);
72//! assert_eq!(block, block_copy);
73//!
74//! // Implementation supports parallel block processing. Number of blocks
75//! // processed in parallel depends in general on hardware capabilities.
76//! // This is achieved by instruction-level parallelism (ILP) on a single
77//! // CPU core, which is different from multi-threaded parallelism.
78//! let mut blocks = [block; 100];
79//! cipher.encrypt_blocks(&mut blocks);
80//!
81//! for block in blocks.iter_mut() {
82//! cipher.decrypt_block(block);
83//! assert_eq!(block, &block_copy);
84//! }
85//!
86//! // `decrypt_blocks` also supports parallel block processing.
87//! cipher.decrypt_blocks(&mut blocks);
88//!
89//! for block in blocks.iter_mut() {
90//! cipher.encrypt_block(block);
91//! assert_eq!(block, &block_copy);
92//! }
93//! ```
94//!
95//! For implementation of block cipher modes of operation see
96//! [`block-modes`] repository.
97//!
98//! # Configuration Flags
99//!
100//! You can modify crate using the following configuration flags:
101//!
102//! - `aes_backend`: explicitly select one of the following backends:
103//! - `soft`: force software backend
104//! - `aes_backend_soft`: modify software backend:
105//! - `compact`: use compact implementation (less performant, but results in a smaller binary)
106//!
107//! It can be enabled using `RUSTFLAGS` environment variable
108//! (e.g. `RUSTFLAGS='--cfg aes_backend="soft"'`) or by modifying `.cargo/config`.
109//!
110//! [AES]: https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
111//! [fixslicing]: https://eprint.iacr.org/2020/1123.pdf
112//! [AES-NI]: https://en.wikipedia.org/wiki/AES_instruction_set
113//! [`block-modes`]: https://github.com/RustCrypto/block-modes/
114
115#![no_std]
116#![doc(
117 html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/26acc39f/logo.svg",
118 html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/26acc39f/logo.svg"
119)]
120#![cfg_attr(docsrs, feature(doc_cfg))]
121#![warn(missing_docs, rust_2018_idioms)]
122
123pub use cipher;
124
125#[cfg(feature = "hazmat")]
126pub mod hazmat;
127
128mod backends;
129
130use cipher::{
131 AlgorithmName, BlockCipherDecClosure, BlockCipherDecrypt, BlockCipherEncClosure,
132 BlockCipherEncrypt, BlockSizeUser, Key, KeyInit, KeySizeUser,
133 array::Array,
134 consts::{U16, U24, U32},
135};
136use core::fmt;
137use cpubits::cfg_if;
138
139/// 128-bit AES block
140pub type Block = Array<u8, U16>;
141
142// Define token used for target feature detection
143cfg_if! {
144 if #[cfg(aes_backend = "soft")] {
145 type Token = ();
146 } else if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] {
147 cpufeatures::new!(features_aes, "aes");
148 cpufeatures::new!(features_vaes256, "vaes");
149 cpufeatures::new!(features_vaes512, "avx512f", "vaes");
150
151 #[derive(Clone, Copy)]
152 struct Token {
153 aes: features_aes::InitToken,
154 vaes256: features_vaes256::InitToken,
155 vaes512: features_vaes512::InitToken,
156 }
157
158 impl Default for Token {
159 fn default() -> Self {
160 Token {
161 aes: features_aes::InitToken::init(),
162 vaes256: features_vaes256::InitToken::init(),
163 vaes512: features_vaes512::InitToken::init(),
164 }
165 }
166 }
167
168 } else if #[cfg(all(target_arch = "aarch64", not(miri)))] {
169 cpufeatures::new!(features_aes, "aes");
170
171 #[derive(Clone, Copy)]
172 struct Token {
173 aes: features_aes::InitToken,
174 }
175
176 impl Default for Token {
177 fn default() -> Self {
178 Token {
179 aes: features_aes::InitToken::init(),
180 }
181 }
182 }
183 } else {
184 type Token = ();
185 }
186}
187
188/// Returns `true` if this crate can use AES hardware acceleration on the current machine.
189///
190/// This is a runtime check performed on the machine where the code is executed.
191///
192/// ```
193/// if aes::hardware_accelerated() {
194/// println!("AES hardware acceleration is available");
195/// } else {
196/// println!("WARNING: using software fallback for AES");
197/// }
198/// ```
199pub fn hardware_accelerated() -> bool {
200 cfg_if! {
201 if #[cfg(aes_backend = "soft")] {
202 false
203 } else if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] {
204 features_aes::get()
205 } else if #[cfg(all(target_arch = "aarch64", not(miri)))] {
206 features_aes::get()
207 } else {
208 false
209 }
210 }
211}
212
213macro_rules! impl_key_init {
214 ($name:ident, $soft_name:ident, $key_size:ty, $inner:path) => {
215 impl KeySizeUser for $name {
216 type KeySize = $key_size;
217 }
218
219 impl KeyInit for $name {
220 #[inline]
221 fn new(key: &Key<Self>) -> Self {
222 type Inner = $inner;
223 let token = Token::default();
224 let key = &key.0;
225
226 #[cfg(not(aes_backend = "soft"))]
227 cfg_if! {
228 if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] {
229 if token.aes.get() {
230 // SAFETY: we confirmed that the required target features are available
231 let aes = unsafe { backends::x86_aes::$name::new(key) };
232 let inner = Inner { aes };
233 return Self { inner, token };
234 }
235 } else if #[cfg(all(target_arch = "aarch64", not(miri)))] {
236 if token.aes.get() {
237 // SAFETY: we confirmed that the required target features are available
238 let aes = unsafe { backends::aarch64_aes::$name::new(key) };
239 let inner = Inner { aes };
240 return Self { inner, token };
241 }
242 }
243 }
244
245 let soft = backends::soft::$soft_name::new(key);
246 let inner = Inner { soft };
247 Self { inner, token }
248 }
249 }
250 };
251}
252
253macro_rules! impl_encrypt {
254 ($ty_name:ident, $name:ident) => {
255 impl BlockCipherEncrypt for $ty_name {
256 #[inline]
257 fn encrypt_with_backend(&self, f: impl BlockCipherEncClosure<BlockSize = U16>) {
258 #[cfg(not(aes_backend = "soft"))]
259 cfg_if! {
260 if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] {
261 if self.token.vaes512.get() {
262 // SAFETY: we access correct union variant
263 let enc_rk = unsafe { &self.inner.aes.enc_rk };
264 // SAFETY: we confirmed that the required target features are available
265 unsafe { backends::x86_vaes512::$name::encrypt(enc_rk, f) };
266 return;
267 }
268
269 if self.token.vaes256.get() {
270 // SAFETY: we access correct union variant
271 let enc_rk = unsafe { &self.inner.aes.enc_rk };
272 // SAFETY: we confirmed that the required target features are available
273 unsafe { backends::x86_vaes256::$name::encrypt(enc_rk, f) };
274 return;
275 }
276
277 if self.token.aes.get() {
278 // SAFETY: we access correct union variant
279 let aes = unsafe { &self.inner.aes };
280 // SAFETY: we confirmed that the required target features are available
281 unsafe { aes.encrypt(f) };
282 return;
283 }
284 } else if #[cfg(all(target_arch = "aarch64", not(miri)))] {
285 if self.token.aes.get() {
286 // SAFETY: we access correct union variant
287 let aes = unsafe { &self.inner.aes };
288 // SAFETY: we confirmed that the required target features are available
289 unsafe { aes.encrypt(f) };
290 return;
291 }
292 }
293 }
294
295 // SAFETY: we access correct union variant
296 let aes = unsafe { &self.inner.soft };
297 aes.encrypt(f);
298 }
299 }
300 };
301}
302
303macro_rules! impl_decrypt {
304 ($name:ident, $alg_name:ident) => {
305 impl BlockCipherDecrypt for $name {
306 #[inline]
307 fn decrypt_with_backend(&self, f: impl BlockCipherDecClosure<BlockSize = U16>) {
308 #[cfg(not(aes_backend = "soft"))]
309 cfg_if! {
310 if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] {
311 if self.token.vaes512.get() {
312 // SAFETY: we access correct union variant
313 let dec_rk = unsafe { &self.inner.aes.dec_rk };
314 // SAFETY: we confirmed that the required target features are available
315 unsafe { backends::x86_vaes512::$alg_name::decrypt(dec_rk, f) };
316 return;
317 }
318
319 if self.token.vaes256.get() {
320 // SAFETY: we access correct union variant
321 let dec_rk = unsafe { &self.inner.aes.dec_rk };
322 // SAFETY: we confirmed that the required target features are available
323 unsafe { backends::x86_vaes256::$alg_name::decrypt(dec_rk, f) };
324 return;
325 }
326
327 if self.token.aes.get() {
328 // SAFETY: we access correct union variant
329 let backend = unsafe { &self.inner.aes };
330 // SAFETY: we confirmed that the required target features are available
331 unsafe { backend.decrypt(f) };
332 return;
333 }
334 } else if #[cfg(all(target_arch = "aarch64", not(miri)))] {
335 if self.token.aes.get() {
336 // SAFETY: we access correct union variant
337 let backend = unsafe { &self.inner.aes };
338 // SAFETY: we confirmed that the required target features are available
339 unsafe { backend.decrypt(f) };
340 return;
341 }
342 }
343 }
344
345 // SAFETY: we access correct union variant
346 let aes = unsafe { &self.inner.soft };
347 aes.decrypt(f);
348 }
349 }
350 };
351}
352
353macro_rules! impl_from_enc {
354 ($name:ident, $name_enc:ident, $inner:path, $into_fn:ident) => {
355 impl From<&$name_enc> for $name {
356 #[inline]
357 fn from(enc: &$name_enc) -> $name {
358 type Inner = $inner;
359
360 let token = enc.token;
361
362 #[cfg(not(aes_backend = "soft"))]
363 cfg_if! {
364 if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] {
365 if token.aes.get() {
366 // SAFETY: we access correct union variant
367 let aes_enc = unsafe { &enc.inner.aes };
368 // SAFETY: we confirmed that the required target features are available
369 let aes = unsafe { aes_enc.$into_fn() };
370 let inner = Inner { aes };
371 return Self { inner, token };
372 }
373 } else if #[cfg(all(target_arch = "aarch64", not(miri)))] {
374 if token.aes.get() {
375 // SAFETY: we access correct union variant
376 let aes_enc = unsafe { &enc.inner.aes };
377 // SAFETY: we confirmed that the required target features are available
378 let aes = unsafe { aes_enc.$into_fn() };
379 let inner = Inner { aes };
380 return Self { inner, token };
381 }
382 }
383 }
384
385 // SAFETY: we access correct union variant
386 let soft = unsafe { enc.inner.soft };
387 let inner = Inner { soft };
388 Self { inner, token }
389 }
390 }
391
392 impl From<$name_enc> for $name {
393 #[inline]
394 fn from(enc: $name_enc) -> $name {
395 Self::from(&enc)
396 }
397 }
398 };
399}
400
401macro_rules! common_impls {
402 ($name:ident) => {
403 impl BlockSizeUser for $name {
404 type BlockSize = U16;
405 }
406
407 impl fmt::Debug for $name {
408 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
409 f.write_str(concat!(stringify!($name), " { .. }"))
410 }
411 }
412
413 impl AlgorithmName for $name {
414 fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
415 f.write_str(stringify!($name))
416 }
417 }
418
419 impl Drop for $name {
420 #[inline]
421 fn drop(&mut self) {
422 #[cfg(feature = "zeroize")]
423 unsafe {
424 zeroize::zeroize_flat_type(self);
425 }
426 }
427 }
428
429 #[cfg(feature = "zeroize")]
430 impl zeroize::ZeroizeOnDrop for $name {}
431 };
432}
433
434macro_rules! define_aes_impl {
435 (
436 name = $name:ident,
437 name_enc = $name_enc:ident,
438 name_dec = $name_dec:ident,
439 module = $module:tt,
440 key_size = $key_size:ident,
441 doc = $doc:expr,
442 ) => {
443 mod $module {
444 use crate::backends;
445
446 #[derive(Copy, Clone)]
447 pub(super) union Inner {
448 #[cfg(all(
449 any(target_arch = "x86_64", target_arch = "x86"),
450 not(aes_backend = "soft"),
451 ))]
452 pub(super) aes: backends::x86_aes::$name,
453 #[cfg(all(target_arch = "aarch64", not(miri), not(aes_backend = "soft")))]
454 pub(super) aes: backends::aarch64_aes::$name,
455 pub(super) soft: backends::soft::$name,
456 }
457
458 #[derive(Copy, Clone)]
459 pub(super) union InnerEnc {
460 #[cfg(all(
461 any(target_arch = "x86_64", target_arch = "x86"),
462 not(aes_backend = "soft"),
463 ))]
464 pub(super) aes: backends::x86_aes::$name_enc,
465 #[cfg(all(target_arch = "aarch64", not(miri), not(aes_backend = "soft")))]
466 pub(super) aes: backends::aarch64_aes::$name_enc,
467 pub(super) soft: backends::soft::$name,
468 }
469
470 #[derive(Copy, Clone)]
471 pub(super) union InnerDec {
472 #[cfg(all(
473 any(target_arch = "x86_64", target_arch = "x86"),
474 not(aes_backend = "soft"),
475 ))]
476 pub(super) aes: backends::x86_aes::$name_dec,
477 #[cfg(all(target_arch = "aarch64", not(miri), not(aes_backend = "soft")))]
478 pub(super) aes: backends::aarch64_aes::$name_dec,
479 pub(super) soft: backends::soft::$name,
480 }
481 }
482
483 #[doc=$doc]
484 #[doc = "block cipher"]
485 #[derive(Clone)]
486 pub struct $name {
487 inner: $module::Inner,
488 #[allow(dead_code, reason = "this field is not used on software-only targets")]
489 token: Token,
490 }
491
492 common_impls!($name);
493 impl_key_init!($name, $name, $key_size, $module::Inner);
494 impl_encrypt!($name, $name);
495 impl_decrypt!($name, $name);
496 impl_from_enc!($name, $name_enc, $module::Inner, as_encdec);
497
498 #[doc=$doc]
499 #[doc = "block cipher (encrypt-only)"]
500 #[derive(Clone)]
501 pub struct $name_enc {
502 inner: $module::InnerEnc,
503 #[allow(dead_code, reason = "this field is not used on software-only targets")]
504 token: Token,
505 }
506
507 common_impls!($name_enc);
508 impl_key_init!($name_enc, $name, $key_size, $module::InnerEnc);
509 impl_encrypt!($name_enc, $name);
510
511 #[doc=$doc]
512 #[doc = "block cipher (decrypt-only)"]
513 #[derive(Clone)]
514 pub struct $name_dec {
515 inner: $module::InnerDec,
516 #[allow(dead_code, reason = "this field is not used on software-only targets")]
517 token: Token,
518 }
519
520 common_impls!($name_dec);
521 impl_key_init!($name_dec, $name, $key_size, $module::InnerDec);
522 impl_decrypt!($name_dec, $name);
523 impl_from_enc!($name_dec, $name_enc, $module::InnerDec, as_dec);
524 };
525}
526
527define_aes_impl!(
528 name = Aes128,
529 name_enc = Aes128Enc,
530 name_dec = Aes128Dec,
531 module = aes128,
532 key_size = U16,
533 doc = "AES-128",
534);
535define_aes_impl!(
536 name = Aes192,
537 name_enc = Aes192Enc,
538 name_dec = Aes192Dec,
539 module = aes192,
540 key_size = U24,
541 doc = "AES-192",
542);
543define_aes_impl!(
544 name = Aes256,
545 name_enc = Aes256Enc,
546 name_dec = Aes256Dec,
547 module = aes256,
548 key_size = U32,
549 doc = "AES-256",
550);