192f3ab15Sopenharmony_ci//! Envelope encryption.
292f3ab15Sopenharmony_ci//!
392f3ab15Sopenharmony_ci//! # Example
492f3ab15Sopenharmony_ci//!
592f3ab15Sopenharmony_ci//! ```rust
692f3ab15Sopenharmony_ci//! use openssl::rsa::Rsa;
792f3ab15Sopenharmony_ci//! use openssl::envelope::Seal;
892f3ab15Sopenharmony_ci//! use openssl::pkey::PKey;
992f3ab15Sopenharmony_ci//! use openssl::symm::Cipher;
1092f3ab15Sopenharmony_ci//!
1192f3ab15Sopenharmony_ci//! let rsa = Rsa::generate(2048).unwrap();
1292f3ab15Sopenharmony_ci//! let key = PKey::from_rsa(rsa).unwrap();
1392f3ab15Sopenharmony_ci//!
1492f3ab15Sopenharmony_ci//! let cipher = Cipher::aes_256_cbc();
1592f3ab15Sopenharmony_ci//! let mut seal = Seal::new(cipher, &[key]).unwrap();
1692f3ab15Sopenharmony_ci//!
1792f3ab15Sopenharmony_ci//! let secret = b"My secret message";
1892f3ab15Sopenharmony_ci//! let mut encrypted = vec![0; secret.len() + cipher.block_size()];
1992f3ab15Sopenharmony_ci//!
2092f3ab15Sopenharmony_ci//! let mut enc_len = seal.update(secret, &mut encrypted).unwrap();
2192f3ab15Sopenharmony_ci//! enc_len += seal.finalize(&mut encrypted[enc_len..]).unwrap();
2292f3ab15Sopenharmony_ci//! encrypted.truncate(enc_len);
2392f3ab15Sopenharmony_ci//! ```
2492f3ab15Sopenharmony_ciuse crate::cipher::CipherRef;
2592f3ab15Sopenharmony_ciuse crate::cipher_ctx::CipherCtx;
2692f3ab15Sopenharmony_ciuse crate::error::ErrorStack;
2792f3ab15Sopenharmony_ciuse crate::pkey::{HasPrivate, HasPublic, PKey, PKeyRef};
2892f3ab15Sopenharmony_ciuse crate::symm::Cipher;
2992f3ab15Sopenharmony_ciuse foreign_types::ForeignTypeRef;
3092f3ab15Sopenharmony_ci
3192f3ab15Sopenharmony_ci/// Represents an EVP_Seal context.
3292f3ab15Sopenharmony_cipub struct Seal {
3392f3ab15Sopenharmony_ci    ctx: CipherCtx,
3492f3ab15Sopenharmony_ci    iv: Option<Vec<u8>>,
3592f3ab15Sopenharmony_ci    enc_keys: Vec<Vec<u8>>,
3692f3ab15Sopenharmony_ci}
3792f3ab15Sopenharmony_ci
3892f3ab15Sopenharmony_ciimpl Seal {
3992f3ab15Sopenharmony_ci    /// Creates a new `Seal`.
4092f3ab15Sopenharmony_ci    pub fn new<T>(cipher: Cipher, pub_keys: &[PKey<T>]) -> Result<Seal, ErrorStack>
4192f3ab15Sopenharmony_ci    where
4292f3ab15Sopenharmony_ci        T: HasPublic,
4392f3ab15Sopenharmony_ci    {
4492f3ab15Sopenharmony_ci        let mut iv = cipher.iv_len().map(|len| vec![0; len]);
4592f3ab15Sopenharmony_ci        let mut enc_keys = vec![vec![]; pub_keys.len()];
4692f3ab15Sopenharmony_ci
4792f3ab15Sopenharmony_ci        let mut ctx = CipherCtx::new()?;
4892f3ab15Sopenharmony_ci        ctx.seal_init(
4992f3ab15Sopenharmony_ci            Some(unsafe { CipherRef::from_ptr(cipher.as_ptr() as *mut _) }),
5092f3ab15Sopenharmony_ci            pub_keys,
5192f3ab15Sopenharmony_ci            &mut enc_keys,
5292f3ab15Sopenharmony_ci            iv.as_deref_mut(),
5392f3ab15Sopenharmony_ci        )?;
5492f3ab15Sopenharmony_ci
5592f3ab15Sopenharmony_ci        Ok(Seal { ctx, iv, enc_keys })
5692f3ab15Sopenharmony_ci    }
5792f3ab15Sopenharmony_ci
5892f3ab15Sopenharmony_ci    /// Returns the initialization vector, if the cipher uses one.
5992f3ab15Sopenharmony_ci    #[allow(clippy::option_as_ref_deref)]
6092f3ab15Sopenharmony_ci    pub fn iv(&self) -> Option<&[u8]> {
6192f3ab15Sopenharmony_ci        self.iv.as_ref().map(|v| &**v)
6292f3ab15Sopenharmony_ci    }
6392f3ab15Sopenharmony_ci
6492f3ab15Sopenharmony_ci    /// Returns the encrypted keys.
6592f3ab15Sopenharmony_ci    pub fn encrypted_keys(&self) -> &[Vec<u8>] {
6692f3ab15Sopenharmony_ci        &self.enc_keys
6792f3ab15Sopenharmony_ci    }
6892f3ab15Sopenharmony_ci
6992f3ab15Sopenharmony_ci    /// Feeds data from `input` through the cipher, writing encrypted bytes into `output`.
7092f3ab15Sopenharmony_ci    ///
7192f3ab15Sopenharmony_ci    /// The number of bytes written to `output` is returned. Note that this may
7292f3ab15Sopenharmony_ci    /// not be equal to the length of `input`.
7392f3ab15Sopenharmony_ci    ///
7492f3ab15Sopenharmony_ci    /// # Panics
7592f3ab15Sopenharmony_ci    ///
7692f3ab15Sopenharmony_ci    /// Panics if `output.len() < input.len() + block_size` where `block_size` is
7792f3ab15Sopenharmony_ci    /// the block size of the cipher (see `Cipher::block_size`), or if
7892f3ab15Sopenharmony_ci    /// `output.len() > c_int::max_value()`.
7992f3ab15Sopenharmony_ci    pub fn update(&mut self, input: &[u8], output: &mut [u8]) -> Result<usize, ErrorStack> {
8092f3ab15Sopenharmony_ci        self.ctx.cipher_update(input, Some(output))
8192f3ab15Sopenharmony_ci    }
8292f3ab15Sopenharmony_ci
8392f3ab15Sopenharmony_ci    /// Finishes the encryption process, writing any remaining data to `output`.
8492f3ab15Sopenharmony_ci    ///
8592f3ab15Sopenharmony_ci    /// The number of bytes written to `output` is returned.
8692f3ab15Sopenharmony_ci    ///
8792f3ab15Sopenharmony_ci    /// `update` should not be called after this method.
8892f3ab15Sopenharmony_ci    ///
8992f3ab15Sopenharmony_ci    /// # Panics
9092f3ab15Sopenharmony_ci    ///
9192f3ab15Sopenharmony_ci    /// Panics if `output` is less than the cipher's block size.
9292f3ab15Sopenharmony_ci    pub fn finalize(&mut self, output: &mut [u8]) -> Result<usize, ErrorStack> {
9392f3ab15Sopenharmony_ci        self.ctx.cipher_final(output)
9492f3ab15Sopenharmony_ci    }
9592f3ab15Sopenharmony_ci}
9692f3ab15Sopenharmony_ci
9792f3ab15Sopenharmony_ci/// Represents an EVP_Open context.
9892f3ab15Sopenharmony_cipub struct Open {
9992f3ab15Sopenharmony_ci    ctx: CipherCtx,
10092f3ab15Sopenharmony_ci}
10192f3ab15Sopenharmony_ci
10292f3ab15Sopenharmony_ciimpl Open {
10392f3ab15Sopenharmony_ci    /// Creates a new `Open`.
10492f3ab15Sopenharmony_ci    pub fn new<T>(
10592f3ab15Sopenharmony_ci        cipher: Cipher,
10692f3ab15Sopenharmony_ci        priv_key: &PKeyRef<T>,
10792f3ab15Sopenharmony_ci        iv: Option<&[u8]>,
10892f3ab15Sopenharmony_ci        encrypted_key: &[u8],
10992f3ab15Sopenharmony_ci    ) -> Result<Open, ErrorStack>
11092f3ab15Sopenharmony_ci    where
11192f3ab15Sopenharmony_ci        T: HasPrivate,
11292f3ab15Sopenharmony_ci    {
11392f3ab15Sopenharmony_ci        let mut ctx = CipherCtx::new()?;
11492f3ab15Sopenharmony_ci        ctx.open_init(
11592f3ab15Sopenharmony_ci            Some(unsafe { CipherRef::from_ptr(cipher.as_ptr() as *mut _) }),
11692f3ab15Sopenharmony_ci            encrypted_key,
11792f3ab15Sopenharmony_ci            iv,
11892f3ab15Sopenharmony_ci            Some(priv_key),
11992f3ab15Sopenharmony_ci        )?;
12092f3ab15Sopenharmony_ci
12192f3ab15Sopenharmony_ci        Ok(Open { ctx })
12292f3ab15Sopenharmony_ci    }
12392f3ab15Sopenharmony_ci
12492f3ab15Sopenharmony_ci    /// Feeds data from `input` through the cipher, writing decrypted bytes into `output`.
12592f3ab15Sopenharmony_ci    ///
12692f3ab15Sopenharmony_ci    /// The number of bytes written to `output` is returned. Note that this may
12792f3ab15Sopenharmony_ci    /// not be equal to the length of `input`.
12892f3ab15Sopenharmony_ci    ///
12992f3ab15Sopenharmony_ci    /// # Panics
13092f3ab15Sopenharmony_ci    ///
13192f3ab15Sopenharmony_ci    /// Panics if `output.len() < input.len() + block_size` where
13292f3ab15Sopenharmony_ci    /// `block_size` is the block size of the cipher (see `Cipher::block_size`),
13392f3ab15Sopenharmony_ci    /// or if `output.len() > c_int::max_value()`.
13492f3ab15Sopenharmony_ci    pub fn update(&mut self, input: &[u8], output: &mut [u8]) -> Result<usize, ErrorStack> {
13592f3ab15Sopenharmony_ci        self.ctx.cipher_update(input, Some(output))
13692f3ab15Sopenharmony_ci    }
13792f3ab15Sopenharmony_ci
13892f3ab15Sopenharmony_ci    /// Finishes the decryption process, writing any remaining data to `output`.
13992f3ab15Sopenharmony_ci    ///
14092f3ab15Sopenharmony_ci    /// The number of bytes written to `output` is returned.
14192f3ab15Sopenharmony_ci    ///
14292f3ab15Sopenharmony_ci    /// `update` should not be called after this method.
14392f3ab15Sopenharmony_ci    ///
14492f3ab15Sopenharmony_ci    /// # Panics
14592f3ab15Sopenharmony_ci    ///
14692f3ab15Sopenharmony_ci    /// Panics if `output` is less than the cipher's block size.
14792f3ab15Sopenharmony_ci    pub fn finalize(&mut self, output: &mut [u8]) -> Result<usize, ErrorStack> {
14892f3ab15Sopenharmony_ci        self.ctx.cipher_final(output)
14992f3ab15Sopenharmony_ci    }
15092f3ab15Sopenharmony_ci}
15192f3ab15Sopenharmony_ci
15292f3ab15Sopenharmony_ci#[cfg(test)]
15392f3ab15Sopenharmony_cimod test {
15492f3ab15Sopenharmony_ci    use super::*;
15592f3ab15Sopenharmony_ci    use crate::pkey::PKey;
15692f3ab15Sopenharmony_ci    use crate::symm::Cipher;
15792f3ab15Sopenharmony_ci
15892f3ab15Sopenharmony_ci    #[test]
15992f3ab15Sopenharmony_ci    fn public_encrypt_private_decrypt() {
16092f3ab15Sopenharmony_ci        let private_pem = include_bytes!("../test/rsa.pem");
16192f3ab15Sopenharmony_ci        let public_pem = include_bytes!("../test/rsa.pem.pub");
16292f3ab15Sopenharmony_ci        let private_key = PKey::private_key_from_pem(private_pem).unwrap();
16392f3ab15Sopenharmony_ci        let public_key = PKey::public_key_from_pem(public_pem).unwrap();
16492f3ab15Sopenharmony_ci        let cipher = Cipher::aes_256_cbc();
16592f3ab15Sopenharmony_ci        let secret = b"My secret message";
16692f3ab15Sopenharmony_ci
16792f3ab15Sopenharmony_ci        let mut seal = Seal::new(cipher, &[public_key]).unwrap();
16892f3ab15Sopenharmony_ci        let mut encrypted = vec![0; secret.len() + cipher.block_size()];
16992f3ab15Sopenharmony_ci        let mut enc_len = seal.update(secret, &mut encrypted).unwrap();
17092f3ab15Sopenharmony_ci        enc_len += seal.finalize(&mut encrypted[enc_len..]).unwrap();
17192f3ab15Sopenharmony_ci        let iv = seal.iv();
17292f3ab15Sopenharmony_ci        let encrypted_key = &seal.encrypted_keys()[0];
17392f3ab15Sopenharmony_ci
17492f3ab15Sopenharmony_ci        let mut open = Open::new(cipher, &private_key, iv, encrypted_key).unwrap();
17592f3ab15Sopenharmony_ci        let mut decrypted = vec![0; enc_len + cipher.block_size()];
17692f3ab15Sopenharmony_ci        let mut dec_len = open.update(&encrypted[..enc_len], &mut decrypted).unwrap();
17792f3ab15Sopenharmony_ci        dec_len += open.finalize(&mut decrypted[dec_len..]).unwrap();
17892f3ab15Sopenharmony_ci
17992f3ab15Sopenharmony_ci        assert_eq!(&secret[..], &decrypted[..dec_len]);
18092f3ab15Sopenharmony_ci    }
18192f3ab15Sopenharmony_ci}
182