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
use crate::{
    key::Key256Bits,
    nonce::{self, NonceSize},
    AssociatedData, Bicrypter, CryptError, Decrypter, Encrypter,
};
use aead::generic_array::GenericArray;
use aead::{Aead, NewAead};
use aes_gcm::Aes256Gcm;

#[derive(Clone)]
pub struct Aes256GcmBicrypter {
    inner: Aes256Gcm,
    nonce_size: NonceSize,
}

/// NOTE: This is purely for derive_builder and should not be used externally
impl Default for Aes256GcmBicrypter {
    fn default() -> Self {
        Self::new(&crate::key::new_256bit_key())
    }
}

impl Aes256GcmBicrypter {
    pub fn new(key: &Key256Bits) -> Self {
        let key = GenericArray::clone_from_slice(key);
        Aes256GcmBicrypter {
            inner: Aes256Gcm::new(key),
            nonce_size: NonceSize::Nonce96Bits,
        }
    }
}

impl Bicrypter for Aes256GcmBicrypter {}

impl Encrypter for Aes256GcmBicrypter {
    fn encrypt(
        &self,
        buffer: &[u8],
        associated_data: &AssociatedData,
    ) -> Result<Vec<u8>, CryptError> {
        let nonce = associated_data
            .nonce_slice()
            .ok_or(CryptError::MissingNonce)?;
        nonce::validate_nonce_size(self.nonce_size, nonce.len())?;
        self.inner
            .encrypt(GenericArray::from_slice(nonce), buffer)
            .map_err(|x| CryptError::EncryptFailed(super::make_error_string(x)))
    }

    /// Returns a new nonce to be associated when encrypting
    fn new_encrypt_associated_data(&self) -> AssociatedData {
        AssociatedData::from(self.nonce_size)
    }
}

impl Decrypter for Aes256GcmBicrypter {
    fn decrypt(
        &self,
        buffer: &[u8],
        associated_data: &AssociatedData,
    ) -> Result<Vec<u8>, CryptError> {
        let nonce = associated_data
            .nonce_slice()
            .ok_or(CryptError::MissingNonce)?;
        nonce::validate_nonce_size(self.nonce_size, nonce.len())?;
        self.inner
            .decrypt(GenericArray::from_slice(nonce), buffer)
            .map_err(|x| CryptError::DecryptFailed(super::make_error_string(x)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::key;
    use crate::nonce::{self, Nonce};
    use crate::{AssociatedData, CryptError, Decrypter, Encrypter};

    #[test]
    fn encrypt_should_fail_if_no_nonce_provided() {
        let bicrypter = Aes256GcmBicrypter::new(&key::new_256bit_key());
        let buffer = vec![1, 2, 3];
        let nonce = AssociatedData::None;

        let result = bicrypter.encrypt(&buffer, &nonce);
        match result {
            Err(CryptError::MissingNonce) => (),
            x => panic!("Unexpected result: {:?}", x),
        }
    }

    #[test]
    fn decrypt_should_fail_if_no_nonce_provided() {
        let bicrypter = Aes256GcmBicrypter::new(&key::new_256bit_key());
        let buffer = vec![1, 2, 3];
        let nonce = AssociatedData::None;

        let result = bicrypter.decrypt(&buffer, &nonce);
        match result {
            Err(CryptError::MissingNonce) => (),
            x => panic!("Unexpected result: {:?}", x),
        }
    }

    #[test]
    fn encrypt_should_fail_if_nonce_is_wrong_size() {
        // Uses 96-bit nonce
        let bicrypter = Aes256GcmBicrypter::new(&key::new_256bit_key());
        let buffer = vec![1, 2, 3];
        let nonce = AssociatedData::Nonce(Nonce::Nonce128Bits(
            nonce::new_128bit_nonce(),
        ));

        let result = bicrypter.encrypt(&buffer, &nonce);
        match result {
            Err(CryptError::NonceWrongSize { provided_size: _ }) => (),
            x => panic!("Unexpected result: {:?}", x),
        }
    }

    #[test]
    fn decrypt_should_fail_if_nonce_is_wrong_size() {
        // Uses 96-bit nonce
        let bicrypter = Aes256GcmBicrypter::new(&key::new_256bit_key());
        let buffer = vec![1, 2, 3];
        let nonce = AssociatedData::Nonce(Nonce::Nonce128Bits(
            nonce::new_128bit_nonce(),
        ));

        let result = bicrypter.decrypt(&buffer, &nonce);
        match result {
            Err(CryptError::NonceWrongSize { provided_size: _ }) => (),
            x => panic!("Unexpected result: {:?}", x),
        }
    }

    #[test]
    fn can_encrypt_and_decrypt() {
        let bicrypter = Aes256GcmBicrypter::new(&key::new_256bit_key());

        let plaintext = b"some message";
        let nonce = nonce::new_96bit_nonce();

        let result = bicrypter.encrypt(
            plaintext,
            &AssociatedData::Nonce(Nonce::Nonce96Bits(nonce)),
        );
        assert!(result.is_ok(), "Failed to encrypt: {:?}", result);

        let result = result.unwrap();
        assert_ne!(
            result, plaintext,
            "Encryption did not alter original message"
        );

        let result = bicrypter
            .decrypt(&result, &AssociatedData::Nonce(Nonce::Nonce96Bits(nonce)))
            .expect("Failed to decrypt");
        assert_eq!(result, plaintext, "Decrypted data is wrong: {:?}", result);
    }
}