libcrux/hacl/
aesgcm.rs

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
use libcrux_hacl::{
    EverCrypt_AEAD_create_in, EverCrypt_AEAD_decrypt, EverCrypt_AEAD_encrypt,
    EverCrypt_AEAD_state_s, EverCrypt_AutoConfig2_init, Spec_Agile_AEAD_AES128_GCM,
    Spec_Agile_AEAD_AES256_GCM,
};

pub type Aes128Key = [u8; 16];
pub type Aes256Key = [u8; 32];
pub type Iv = [u8; 12];
pub type Tag = [u8; 16];

/// AES GCM Errors
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Error {
    /// The hardware does not support the required features.
    UnsupportedHardware,

    /// Encryption failed because the provided arguments were not valid.
    EncryptionError,

    /// Decryption failed.
    InvalidCiphertext,
}

/// Check if the hardware supports the required features.
/// This uses the evercrypt feature detection.
pub fn hardware_support() -> Result<(), Error> {
    unsafe {
        EverCrypt_AutoConfig2_init();
        if libcrux_hacl::EverCrypt_AutoConfig2_has_aesni()
            && libcrux_hacl::EverCrypt_AutoConfig2_has_pclmulqdq()
            && libcrux_hacl::EverCrypt_AutoConfig2_has_avx()
            && libcrux_hacl::EverCrypt_AutoConfig2_has_sse()
            && libcrux_hacl::EverCrypt_AutoConfig2_has_movbe()
        {
            Ok(())
        } else {
            Err(Error::UnsupportedHardware)
        }
    }
}

macro_rules! implement {
    ($name:ident, $name_dec:ident, $alg:expr, $keytype:ty) => {
        /// Encrypt the payload in `msg_ctxt` with the provided `key`, `iv`, and
        /// `aad`.
        ///
        /// Returns the ciphertext in `msg_ctx` and the `Tag`, or an `Error` if
        /// the provided arguments are not valid.
        #[must_use]
        pub fn $name(
            key: &$keytype,
            msg_ctxt: &mut [u8],
            iv: Iv,
            aad: &[u8],
        ) -> Result<Tag, Error> {
            let mut tag = Tag::default();
            hardware_support()?;
            let ok = unsafe {
                let mut state_ptr: *mut EverCrypt_AEAD_state_s = std::ptr::null_mut();
                let e = EverCrypt_AEAD_create_in($alg as u8, &mut state_ptr, key.as_ptr() as _);
                if e != 0 {
                    return Err(Error::EncryptionError);
                }
                EverCrypt_AEAD_encrypt(
                    state_ptr,
                    iv.as_ptr() as _,
                    iv.len().try_into().map_err(|_| Error::EncryptionError)?,
                    aad.as_ptr() as _,
                    aad.len().try_into().map_err(|_| Error::EncryptionError)?,
                    msg_ctxt.as_ptr() as _,
                    msg_ctxt
                        .len()
                        .try_into()
                        .map_err(|_| Error::EncryptionError)?,
                    msg_ctxt.as_mut_ptr(),
                    tag.as_mut_ptr(),
                )
            };
            if ok == 0 {
                Ok(tag)
            } else {
                Err(Error::EncryptionError)
            }
        }

        /// Decrypt the ciphertext in `payload` with the provided `key`, `iv`, and
        /// `aad`.
        ///
        /// Returns the plaintext in `payload` if decryption is successful or
        /// an `Error`.
        #[must_use]
        pub fn $name_dec(
            key: &$keytype,
            payload: &mut [u8],
            iv: Iv,
            aad: &[u8],
            tag: &Tag,
        ) -> Result<(), Error> {
            hardware_support()?;
            let ok = unsafe {
                let mut state_ptr: *mut EverCrypt_AEAD_state_s = std::ptr::null_mut();
                let e = EverCrypt_AEAD_create_in($alg as u8, &mut state_ptr, key.as_ptr() as _);
                if e != 0 {
                    return Err(Error::EncryptionError);
                }
                EverCrypt_AEAD_decrypt(
                    state_ptr,
                    iv.as_ptr() as _,
                    iv.len().try_into().map_err(|_| Error::EncryptionError)?,
                    aad.as_ptr() as _,
                    aad.len().try_into().map_err(|_| Error::EncryptionError)?,
                    payload.as_ptr() as _,
                    payload
                        .len()
                        .try_into()
                        .map_err(|_| Error::EncryptionError)?,
                    tag.as_ptr() as _,
                    payload.as_mut_ptr(),
                )
            };
            if ok == 0 {
                Ok(())
            } else {
                Err(Error::InvalidCiphertext)
            }
        }
    };
}

implement!(
    encrypt_128,
    decrypt_128,
    Spec_Agile_AEAD_AES128_GCM,
    Aes128Key
);
implement!(
    encrypt_256,
    decrypt_256,
    Spec_Agile_AEAD_AES256_GCM,
    Aes256Key
);