askar_crypto/encrypt/
mod.rs

1//! AEAD encryption traits and parameters
2
3use crate::{buffer::ResizeBuffer, error::Error, generic_array::ArrayLength};
4
5#[cfg(feature = "getrandom")]
6use crate::generic_array::GenericArray;
7
8#[cfg(feature = "crypto_box")]
9#[cfg_attr(docsrs, doc(cfg(feature = "crypto_box")))]
10pub mod crypto_box;
11
12/// Object-safe trait for key types which perform AEAD encryption
13pub trait KeyAeadInPlace {
14    /// Encrypt a secret value in place, appending the verification tag and
15    /// returning the length of the ciphertext
16    fn encrypt_in_place(
17        &self,
18        buffer: &mut dyn ResizeBuffer,
19        nonce: &[u8],
20        aad: &[u8],
21    ) -> Result<usize, Error>;
22
23    /// Decrypt an encrypted (verification tag appended) value in place
24    fn decrypt_in_place(
25        &self,
26        buffer: &mut dyn ResizeBuffer,
27        nonce: &[u8],
28        aad: &[u8],
29    ) -> Result<(), Error>;
30
31    /// Get the nonce and tag length for encryption
32    fn aead_params(&self) -> KeyAeadParams;
33
34    /// Get the ciphertext padding required
35    fn aead_padding(&self, _msg_len: usize) -> usize {
36        0
37    }
38}
39
40/// For concrete key types with fixed nonce and tag sizes
41pub trait KeyAeadMeta {
42    /// The size of the AEAD nonce
43    type NonceSize: ArrayLength<u8>;
44    /// The size of the AEAD tag
45    type TagSize: ArrayLength<u8>;
46
47    /// Generate a new random nonce
48    #[cfg(feature = "getrandom")]
49    fn random_nonce() -> GenericArray<u8, Self::NonceSize> {
50        let mut nonce = GenericArray::default();
51        crate::random::fill_random(nonce.as_mut_slice());
52        nonce
53    }
54}
55
56/// A structure combining the AEAD parameters
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
58pub struct KeyAeadParams {
59    /// The length of the nonce
60    pub nonce_length: usize,
61    /// The length of the tag
62    pub tag_length: usize,
63}