1#![cfg(any(
16 all(target_arch = "aarch64", target_endian = "little"),
17 target_arch = "x86",
18 target_arch = "x86_64"
19))]
20
21use super::{Block, Counter, EncryptBlock, EncryptCtr32, Iv, KeyBytes, Overlapping, AES_KEY};
22use crate::{cpu, error};
23use cfg_if::cfg_if;
24
25cfg_if! {
26 if #[cfg(all(target_arch = "aarch64", target_endian = "little"))] {
27 pub(in super::super) type RequiredCpuFeatures = cpu::arm::Aes;
28 pub(in super::super) type OptionalCpuFeatures = ();
29 } else if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
30 use cpu::intel::{Aes, Avx, Ssse3};
31 pub(in super::super) type RequiredCpuFeatures = (Aes, Ssse3);
35 pub(in super::super) type OptionalCpuFeatures = Avx;
36 }
37}
38
39#[derive(Clone)]
40pub struct Key {
41 inner: AES_KEY,
42}
43
44impl Key {
45 #[cfg(all(target_arch = "aarch64", target_endian = "little"))]
46 pub(in super::super) fn new(
47 bytes: KeyBytes<'_>,
48 _required_cpu_features: RequiredCpuFeatures,
49 _optional_cpu_features: Option<OptionalCpuFeatures>,
50 ) -> Result<Self, error::Unspecified> {
51 let inner = unsafe { set_encrypt_key!(aes_hw_set_encrypt_key, bytes) }?;
52 Ok(Self { inner })
53 }
54
55 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
56 pub(in super::super) fn new(
57 bytes: KeyBytes<'_>,
58 (Aes { .. }, Ssse3 { .. }): RequiredCpuFeatures,
59 optional_cpu_features: Option<OptionalCpuFeatures>,
60 ) -> Result<Self, error::Unspecified> {
61 let inner = if let Some(Avx { .. }) = optional_cpu_features {
64 unsafe { set_encrypt_key!(aes_hw_set_encrypt_key_alt, bytes) }?
65 } else {
66 unsafe { set_encrypt_key!(aes_hw_set_encrypt_key_base, bytes) }?
67 };
68 Ok(Self { inner })
69 }
70
71 #[cfg(any(
72 all(target_arch = "aarch64", target_endian = "little"),
73 target_arch = "x86_64"
74 ))]
75 #[must_use]
76 pub(in super::super) fn inner_less_safe(&self) -> &AES_KEY {
77 &self.inner
78 }
79}
80
81impl EncryptBlock for Key {
82 fn encrypt_block(&self, block: Block) -> Block {
83 super::encrypt_block_using_encrypt_iv_xor_block(self, block)
84 }
85
86 fn encrypt_iv_xor_block(&self, iv: Iv, block: Block) -> Block {
87 super::encrypt_iv_xor_block_using_ctr32(self, iv, block)
88 }
89}
90
91impl EncryptCtr32 for Key {
92 fn ctr32_encrypt_within(&self, in_out: Overlapping<'_>, ctr: &mut Counter) {
93 unsafe { ctr32_encrypt_blocks!(aes_hw_ctr32_encrypt_blocks, in_out, &self.inner, ctr) }
94 }
95}