aes 0.9.2

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

#![no_std]
#![doc(
    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/26acc39f/logo.svg",
    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/26acc39f/logo.svg"
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(missing_docs, rust_2018_idioms)]

pub use cipher;

#[cfg(feature = "hazmat")]
pub mod hazmat;

mod backends;

use cipher::{
    AlgorithmName, BlockCipherDecClosure, BlockCipherDecrypt, BlockCipherEncClosure,
    BlockCipherEncrypt, BlockSizeUser, Key, KeyInit, KeySizeUser,
    array::Array,
    consts::{U16, U24, U32},
};
use core::fmt;
use cpubits::cfg_if;

/// 128-bit AES block
pub type Block = Array<u8, U16>;

// Define token used for target feature detection
cfg_if! {
    if #[cfg(aes_backend = "soft")] {
        type Token = ();
    } else if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] {
        cpufeatures::new!(features_aes, "aes");
        #[cfg(any(aes_backend = "avx256", aes_backend = "avx512"))]
        cpufeatures::new!(features_vaes256, "vaes");
        #[cfg(aes_backend = "avx512")]
        cpufeatures::new!(features_vaes512, "avx512f", "vaes");

        #[derive(Clone, Copy)]
        struct Token {
            aes: features_aes::InitToken,
            #[cfg(any(aes_backend = "avx256", aes_backend = "avx512"))]
            vaes256: features_vaes256::InitToken,
            #[cfg(aes_backend = "avx512")]
            vaes512: features_vaes512::InitToken,
        }

        impl Default for Token {
            fn default() -> Self {
                Token {
                    aes: features_aes::InitToken::init(),
                    #[cfg(any(aes_backend = "avx256", aes_backend = "avx512"))]
                    vaes256: features_vaes256::InitToken::init(),
                    #[cfg(aes_backend = "avx512")]
                    vaes512: features_vaes512::InitToken::init(),
                }
            }
        }

    } else if #[cfg(target_arch = "aarch64")] {
        cpufeatures::new!(features_aes, "aes");

        #[derive(Clone, Copy)]
        struct Token {
            aes: features_aes::InitToken,
        }

        impl Default for Token {
            fn default() -> Self {
                Token {
                    aes: features_aes::InitToken::init(),
                }
            }
        }
    } else {
        type Token = ();
    }
}

/// Returns `true` if this crate can use AES hardware acceleration on the current machine.
///
/// This is a runtime check performed on the machine where the code is executed.
///
/// ```
/// if aes::hardware_accelerated() {
///     println!("AES hardware acceleration is available");
/// } else {
///     println!("WARNING: using software fallback for AES");
/// }
/// ```
pub fn hardware_accelerated() -> bool {
    cfg_if! {
        if #[cfg(aes_backend = "soft")] {
            false
        } else if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] {
            features_aes::get()
        } else if #[cfg(target_arch = "aarch64")] {
            features_aes::get()
        } else {
            false
        }
    }
}

macro_rules! impl_key_init {
    ($name:ident, $soft_name:ident, $key_size:ty, $inner:path) => {
        impl KeySizeUser for $name {
            type KeySize = $key_size;
        }

        impl KeyInit for $name {
            #[inline]
            fn new(key: &Key<Self>) -> Self {
                type Inner = $inner;
                let token = Token::default();
                let key = &key.0;

                #[cfg(not(aes_backend = "soft"))]
                cfg_if! {
                    if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] {
                        if token.aes.get() {
                            // SAFETY: we confirmed that the required target features are available
                            let aes = unsafe { backends::x86_aes::$name::new(key) };
                            let inner = Inner { aes };
                            return Self { inner, token };
                        }
                    } else if #[cfg(target_arch = "aarch64")] {
                        if token.aes.get() {
                            // SAFETY: we confirmed that the required target features are available
                            let aes = unsafe { backends::aarch64_aes::$name::new(key) };
                            let inner = Inner { aes };
                            return Self { inner, token };
                        }
                    }
                }

                let soft = backends::soft::$soft_name::new(key);
                let inner = Inner { soft };
                Self { inner, token }
            }
        }
    };
}

macro_rules! impl_encrypt {
    ($ty_name:ident, $name:ident) => {
        impl BlockCipherEncrypt for $ty_name {
            #[inline]
            fn encrypt_with_backend(&self, f: impl BlockCipherEncClosure<BlockSize = U16>) {
                #[cfg(not(aes_backend = "soft"))]
                cfg_if! {
                    if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] {
                        #[cfg(aes_backend = "avx512")]
                        if self.token.vaes512.get() {
                            // SAFETY: we access correct union variant
                            let enc_rk = unsafe { &self.inner.aes.enc_rk };
                            // SAFETY: we confirmed that the required target features are available
                            unsafe { backends::x86_vaes512::$name::encrypt(enc_rk, f) };
                            return;
                        }

                        #[cfg(any(aes_backend = "avx256", aes_backend = "avx512"))]
                        if self.token.vaes256.get() {
                            // SAFETY: we access correct union variant
                            let enc_rk = unsafe { &self.inner.aes.enc_rk };
                            // SAFETY: we confirmed that the required target features are available
                            unsafe { backends::x86_vaes256::$name::encrypt(enc_rk, f) };
                            return;
                        }

                        if self.token.aes.get() {
                            // SAFETY: we access correct union variant
                            let aes = unsafe { &self.inner.aes };
                            // SAFETY: we confirmed that the required target features are available
                            unsafe { aes.encrypt(f) };
                            return;
                        }
                    } else if #[cfg(target_arch = "aarch64")] {
                        if self.token.aes.get() {
                            // SAFETY: we access correct union variant
                            let aes = unsafe { &self.inner.aes };
                            // SAFETY: we confirmed that the required target features are available
                            unsafe { aes.encrypt(f) };
                            return;
                        }
                    }
                }

                // SAFETY: we access correct union variant
                let backend = unsafe { &self.inner.soft };
                f.call(backend);
            }
        }
    };
}

macro_rules! impl_decrypt {
    ($name:ident, $alg_name:ident) => {
        impl BlockCipherDecrypt for $name {
            #[inline]
            fn decrypt_with_backend(&self, f: impl BlockCipherDecClosure<BlockSize = U16>) {
                #[cfg(not(aes_backend = "soft"))]
                cfg_if! {
                    if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] {
                        #[cfg(aes_backend = "avx512")]
                        if self.token.vaes512.get() {
                            // SAFETY: we access correct union variant
                            let dec_rk = unsafe { &self.inner.aes.dec_rk };
                            // SAFETY: we confirmed that the required target features are available
                            unsafe { backends::x86_vaes512::$alg_name::decrypt(dec_rk, f) };
                            return;
                        }

                        #[cfg(any(aes_backend = "avx256", aes_backend = "avx512"))]
                        if self.token.vaes256.get() {
                            // SAFETY: we access correct union variant
                            let dec_rk = unsafe { &self.inner.aes.dec_rk };
                            // SAFETY: we confirmed that the required target features are available
                            unsafe { backends::x86_vaes256::$alg_name::decrypt(dec_rk, f) };
                            return;
                        }

                        if self.token.aes.get() {
                            // SAFETY: we access correct union variant
                            let backend = unsafe { &self.inner.aes };
                            // SAFETY: we confirmed that the required target features are available
                            unsafe { backend.decrypt(f) };
                            return;
                        }
                    } else if #[cfg(target_arch = "aarch64")] {
                        if self.token.aes.get() {
                            // SAFETY: we access correct union variant
                            let backend = unsafe { &self.inner.aes };
                            // SAFETY: we confirmed that the required target features are available
                            unsafe { backend.decrypt(f) };
                            return;
                        }
                    }
                }

                // SAFETY: we access correct union variant
                let backend = unsafe { &self.inner.soft };
                f.call(backend);
            }
        }
    };
}

macro_rules! impl_from_enc {
    ($name:ident, $name_enc:ident, $inner:path, $into_fn:ident) => {
        impl From<&$name_enc> for $name {
            #[inline]
            fn from(enc: &$name_enc) -> $name {
                type Inner = $inner;

                let token = enc.token;

                #[cfg(not(aes_backend = "soft"))]
                cfg_if! {
                    if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] {
                        if token.aes.get() {
                            // SAFETY: we access correct union variant
                            let aes_enc = unsafe { &enc.inner.aes };
                            // SAFETY: we confirmed that the required target features are available
                            let aes = unsafe { aes_enc.$into_fn() };
                            let inner = Inner { aes };
                            return Self { inner, token };
                        }
                    } else if #[cfg(target_arch = "aarch64")] {
                        if token.aes.get() {
                            // SAFETY: we access correct union variant
                            let aes_enc = unsafe { &enc.inner.aes };
                            // SAFETY: we confirmed that the required target features are available
                            let aes = unsafe { aes_enc.$into_fn() };
                            let inner = Inner { aes };
                            return Self { inner, token };
                        }
                    }
                }

                // SAFETY: we access correct union variant
                let soft = unsafe { enc.inner.soft };
                let inner = Inner { soft };
                Self { inner, token }
            }
        }

        impl From<$name_enc> for $name {
            #[inline]
            fn from(enc: $name_enc) -> $name {
                Self::from(&enc)
            }
        }
    };
}

macro_rules! common_impls {
    ($name:ident) => {
        impl BlockSizeUser for $name {
            type BlockSize = U16;
        }

        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
                f.write_str(concat!(stringify!($name), " { .. }"))
            }
        }

        impl AlgorithmName for $name {
            fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(stringify!($name))
            }
        }

        impl Drop for $name {
            #[inline]
            fn drop(&mut self) {
                #[cfg(feature = "zeroize")]
                unsafe {
                    zeroize::zeroize_flat_type(self);
                }
            }
        }

        #[cfg(feature = "zeroize")]
        impl zeroize::ZeroizeOnDrop for $name {}
    };
}

macro_rules! define_aes_impl {
    (
        name = $name:ident,
        name_enc = $name_enc:ident,
        name_dec = $name_dec:ident,
        module = $module:tt,
        key_size = $key_size:ident,
        doc = $doc:expr,
    ) => {
        mod $module {
            use crate::backends;

            #[derive(Copy, Clone)]
            pub(super) union Inner {
                #[cfg(all(
                    any(target_arch = "x86_64", target_arch = "x86"),
                    not(aes_backend = "soft"),
                ))]
                pub(super) aes: backends::x86_aes::$name,
                #[cfg(all(target_arch = "aarch64", not(aes_backend = "soft")))]
                pub(super) aes: backends::aarch64_aes::$name,
                pub(super) soft: backends::soft::$name,
            }

            #[derive(Copy, Clone)]
            pub(super) union InnerEnc {
                #[cfg(all(
                    any(target_arch = "x86_64", target_arch = "x86"),
                    not(aes_backend = "soft"),
                ))]
                pub(super) aes: backends::x86_aes::$name_enc,
                #[cfg(all(target_arch = "aarch64", not(aes_backend = "soft")))]
                pub(super) aes: backends::aarch64_aes::$name_enc,
                pub(super) soft: backends::soft::$name,
            }

            #[derive(Copy, Clone)]
            pub(super) union InnerDec {
                #[cfg(all(
                    any(target_arch = "x86_64", target_arch = "x86"),
                    not(aes_backend = "soft"),
                ))]
                pub(super) aes: backends::x86_aes::$name_dec,
                #[cfg(all(target_arch = "aarch64", not(aes_backend = "soft")))]
                pub(super) aes: backends::aarch64_aes::$name_dec,
                pub(super) soft: backends::soft::$name,
            }
        }

        #[doc=$doc]
        #[doc = "block cipher"]
        #[derive(Clone)]
        pub struct $name {
            inner: $module::Inner,
            #[allow(dead_code, reason = "this field is not used on software-only targets")]
            token: Token,
        }

        common_impls!($name);
        impl_key_init!($name, $name, $key_size, $module::Inner);
        impl_encrypt!($name, $name);
        impl_decrypt!($name, $name);
        impl_from_enc!($name, $name_enc, $module::Inner, as_encdec);

        #[doc=$doc]
        #[doc = "block cipher (encrypt-only)"]
        #[derive(Clone)]
        pub struct $name_enc {
            inner: $module::InnerEnc,
            #[allow(dead_code, reason = "this field is not used on software-only targets")]
            token: Token,
        }

        common_impls!($name_enc);
        impl_key_init!($name_enc, $name, $key_size, $module::InnerEnc);
        impl_encrypt!($name_enc, $name);

        #[doc=$doc]
        #[doc = "block cipher (decrypt-only)"]
        #[derive(Clone)]
        pub struct $name_dec {
            inner: $module::InnerDec,
            #[allow(dead_code, reason = "this field is not used on software-only targets")]
            token: Token,
        }

        common_impls!($name_dec);
        impl_key_init!($name_dec, $name, $key_size, $module::InnerDec);
        impl_decrypt!($name_dec, $name);
        impl_from_enc!($name_dec, $name_enc, $module::InnerDec, as_dec);
    };
}

define_aes_impl!(
    name = Aes128,
    name_enc = Aes128Enc,
    name_dec = Aes128Dec,
    module = aes128,
    key_size = U16,
    doc = "AES-128",
);
define_aes_impl!(
    name = Aes192,
    name_enc = Aes192Enc,
    name_dec = Aes192Dec,
    module = aes192,
    key_size = U24,
    doc = "AES-192",
);
define_aes_impl!(
    name = Aes256,
    name_enc = Aes256Enc,
    name_dec = Aes256Dec,
    module = aes256,
    key_size = U32,
    doc = "AES-256",
);