summaryrefslogtreecommitdiffstats
path: root/openpgp/src/crypto/backend/nettle/aead.rs
blob: e7ae9d85e6f92de374b15f34e4d2f612dc829164 (plain)
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
//! Implementation of AEAD using Nettle cryptographic library.
use nettle::{aead, cipher};

use crate::{Error, Result};

use crate::crypto::aead::{Aead, CipherOp};
use crate::seal;
use crate::types::{AEADAlgorithm, SymmetricAlgorithm};

impl<T: nettle::aead::Aead> seal::Sealed for T {}
impl<T: nettle::aead::Aead> Aead for T {
    fn update(&mut self, ad: &[u8]) {
        self.update(ad)
    }
    fn encrypt(&mut self, dst: &mut [u8], src: &[u8]) {
        self.encrypt(dst, src)
    }
    fn decrypt(&mut self, dst: &mut [u8], src: &[u8]) {
        self.decrypt(dst, src)
    }
    fn digest(&mut self, digest: &mut [u8]) {
        self.digest(digest)
    }
    fn digest_size(&self) -> usize {
        self.digest_size()
    }
}

impl AEADAlgorithm {
    pub(crate) fn context(
        &self,
        sym_algo: SymmetricAlgorithm,
        key: &[u8],
        nonce: &[u8],
        _op: CipherOp,
    ) -> Result<Box<dyn Aead>> {
        match self {
            AEADAlgorithm::EAX => match sym_algo {
                SymmetricAlgorithm::AES128 => Ok(Box::new(
                    aead::Eax::<cipher::Aes128>::with_key_and_nonce(key, nonce)?,
                )),
                SymmetricAlgorithm::AES192 => Ok(Box::new(
                    aead::Eax::<cipher::Aes192>::with_key_and_nonce(key, nonce)?,
                )),
                SymmetricAlgorithm::AES256 => Ok(Box::new(
                    aead::Eax::<cipher::Aes256>::with_key_and_nonce(key, nonce)?,
                )),
                SymmetricAlgorithm::Twofish => Ok(Box::new(
                    aead::Eax::<cipher::Twofish>::with_key_and_nonce(key, nonce)?,
                )),
                SymmetricAlgorithm::Camellia128 => Ok(Box::new(
                    aead::Eax::<cipher::Camellia128>::with_key_and_nonce(key, nonce)?,
                )),
                SymmetricAlgorithm::Camellia192 => Ok(Box::new(
                    aead::Eax::<cipher::Camellia192>::with_key_and_nonce(key, nonce)?,
                )),
                SymmetricAlgorithm::Camellia256 => Ok(Box::new(
                    aead::Eax::<cipher::Camellia256>::with_key_and_nonce(key, nonce)?,
                )),
                _ => Err(Error::UnsupportedSymmetricAlgorithm(sym_algo).into()),
            },
            _ => Err(Error::UnsupportedAEADAlgorithm(*self).into()),
        }
    }
}