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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
use crate::{
    error::{Error, Result},
    keepers::SecretKeeper,
    AuthTag, WrappedKey,
};
use async_trait::async_trait;
use bytes::Bytes;
// use serde_repr::{Deserialize_repr, Serialize_repr};
use std::fmt;
use strum_macros::{Display, EnumString};
use tokio::fs::File;

/// Compressing cipher that compresses data before encrypting.
#[async_trait]
pub trait CompressingCipher: Cipher {
    /// Compress and encrypt the slice, with optional associated data.
    async fn seal_compressed(
        &self,
        src: &[u8],
        aad: Option<&[u8]>,
    ) -> Result<(Bytes, AuthTag), Error>;

    /// Decrypt slice into the provided buffer.
    /// src: compressed ciphertext
    /// tag: auth tag
    /// size_hint: optional size used to allocate buffer for result
    async fn open_compressed(
        &self,
        src: &mut [u8],
        tag: &[u8],
        size_hint: Option<u64>,
        aad: Option<&[u8]>,
    ) -> Result<Bytes, Error>;
}

/// Describes interface to encrypt/decrypt file
#[async_trait]
pub trait Cipher: fmt::Debug + Sync + Send {
    /// Returns whether or not this encryption supports aad
    fn supports_aad(&self) -> bool;

    /// Encrypts the slice, with optional authenticated data
    /// Return value is a simple vector that contains the ciphertext
    /// plus a MAC-based authentication tag.
    async fn seal(&self, plaintext: &[u8], aad: Option<&[u8]>) -> Result<Bytes, Error>;

    /// Decrypts the slice. The ciphertext buffer was
    /// created with seal(), and contains an appended auth tag.
    /// For CompressingCipher, this method may be less efficient than open_detached,
    /// because it needs to make two heap allocs: one for decryption, and one for decompression.
    /// If you can use open_detached, the decryption is done in place so the first alloc
    /// is avoided. Return value is the decrypted plaintext.
    async fn open(&self, ciphertext: &[u8], aad: Option<&[u8]>) -> Result<Bytes, Error>;

    /// Encrypt the file, with optional associated data.
    /// Return tuple has encrypted data, auth tag, and file size
    async fn seal_file(
        &self,
        file_path: &str,
        aad: Option<&[u8]>,
    ) -> Result<(Bytes, AuthTag, u64), Error>;

    /// Encrypt the data and write/append to the file. Returns the auth tag and length of data appended
    /// data buf may be overwritten for encryption-in-place
    async fn seal_write(
        &self,
        data: &mut [u8],
        file: &mut File,
        aad: Option<&[u8]>,
    ) -> Result<(AuthTag, u64), Error>;

    /// Encrypt the slice, with optional associated data.
    /// The data is encrypted in place.
    /// The tag returned must be used with open_detached
    async fn seal_detached(&self, src: &mut [u8], aad: Option<&[u8]>) -> Result<AuthTag, Error>;

    /// Read len bytes from the file, decrypt, and return.
    /// To reduce memory allocations, (particularly for compressing ciphers),
    /// caller should set size_hint to size of decompressed/decrypted data, if known.
    /// For non-compressing cipher such as xchacha20-poly1305, return Bytes.len() == len
    async fn open_read(
        &self,
        file: &mut File,
        len: u64,
        size_hint: Option<u64>,
        tag: &[u8],
        aad: Option<&[u8]>,
    ) -> Result<Bytes, Error>;

    /// Decrypts slice in-place.
    /// buf: mutable buffer containing ciphertext (in), to be overwritten with plaintext
    /// tag: auth tag data
    /// aad: optional associated data
    async fn open_detached(
        &self,
        buf: &mut [u8],
        tag: &[u8],
        aad: Option<&[u8]>,
    ) -> Result<(), Error>;

    /// Export key by encrypting and wrapping it
    async fn export(
        &self,
        uri: &str,
        nonce: &[u8],
        keeper: &Box<dyn SecretKeeper>,
    ) -> Result<WrappedKey, Error>;

    // the methods below here are auto-generated by the cipher_impl macro
    //
    /// number of bytes in nonce for this cipher
    fn nonce_len(&self) -> usize;

    /// number of bytes in key for this cipher
    fn key_len(&self) -> usize;

    /// number of bytes in tag
    fn tag_len(&self) -> usize;

    /// return nonce as slice
    fn get_nonce(&self) -> &[u8];
}

/// Trait for cipher that can import keys
#[async_trait]
pub trait Import: Cipher + Sized {
    /// Import key by unwrapping and decrypting it
    async fn import(
        nonce: &[u8],
        keeper: &Box<dyn SecretKeeper>,
        wrapped: &WrappedKey,
    ) -> Result<Self, Error>;
}

/// Encryption cipher algorithm
#[derive(Clone, Debug, Display, PartialEq, EnumString)]
pub enum CipherKind {
    /// aes-gcm encryption with 256-bit key
    #[strum( // multiple synonyms for FromStr
        to_string = "AesGcm256",
        serialize = "aes",
        serialize = "aesgcm",
        serialize = "aesgcm256"
    )]
    AesGcm256,

    /// xchacha20-poly1305
    #[strum( // multiple synonyms for FromStr
        to_string = "XChaCha20Poly1305",
        serialize = "xchacha20",
        serialize = "xchacha20poly1305"
    )]
    XChaCha20Poly1305,

    /// xchacha20-poly1305 with lz4 compression
    #[strum( // multiple synonyms for FromStr
        to_string = "LZ4XChaCha20Poly1305",
        serialize = "lz4",
        serialize = "lz4xchacha20",
        serialize = "lz4xchacha20poly1305"
    )]
    LZ4XChaCha20Poly1305,
}

//
// custom Serialization,Deserialization for CipherKind so that it uses a known size (u8)
//

const KIND_AESGCM256: u8 = 1;
const KIND_XCHACHA20POLY1305: u8 = 2;
const KIND_LZ4XCHACHA20POLY1305: u8 = 3;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

impl Serialize for CipherKind {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u8(match *self {
            CipherKind::AesGcm256 => KIND_AESGCM256,
            CipherKind::XChaCha20Poly1305 => KIND_XCHACHA20POLY1305,
            CipherKind::LZ4XChaCha20Poly1305 => KIND_LZ4XCHACHA20POLY1305,
        })
    }
}

impl<'de> Deserialize<'de> for CipherKind {
    fn deserialize<D>(deserializer: D) -> Result<CipherKind, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_u8(CipherKindVisitor)
    }
}

struct CipherKindVisitor;
impl<'de> serde::de::Visitor<'de> for CipherKindVisitor {
    type Value = CipherKind;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("u8 from 1 to 3")
    }

    fn visit_u8<E>(self, n: u8) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        match n {
            KIND_AESGCM256 => Ok(CipherKind::AesGcm256),
            KIND_XCHACHA20POLY1305 => Ok(CipherKind::XChaCha20Poly1305),
            KIND_LZ4XCHACHA20POLY1305 => Ok(CipherKind::LZ4XChaCha20Poly1305),
            _ => Err(E::custom(format!("u8 is not a valid CipherKind id: {}", n))),
        }
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::error::{Error, Result};
    use bincode;

    fn ser_de(k: CipherKind, v: u8) -> Result<(), Error> {
        let buf = bincode::serialize(&k)?;
        assert_eq!(buf.len(), 1, "serialize {}", k.to_string());
        assert_eq!(buf[0], v, "serialize {} to value", k.to_string());
        let y: CipherKind = bincode::deserialize(&buf)?;
        assert_eq!(y, k, "deserialize {}", k.to_string());
        Ok(())
    }

    #[test]
    fn cipher_kind_ser_de() -> Result<(), Error> {
        ser_de(CipherKind::AesGcm256, KIND_AESGCM256)?;
        ser_de(CipherKind::XChaCha20Poly1305, KIND_XCHACHA20POLY1305)?;
        ser_de(CipherKind::LZ4XChaCha20Poly1305, KIND_LZ4XCHACHA20POLY1305)?;
        Ok(())
    }
}