1//! Envelope encryption.
2//!
3//! # Example
4//!
5//! ```rust
6//! use openssl::rsa::Rsa;
7//! use openssl::envelope::Seal;
8//! use openssl::pkey::PKey;
9//! use openssl::symm::Cipher;
10//!
11//! let rsa = Rsa::generate(2048).unwrap();
12//! let key = PKey::from_rsa(rsa).unwrap();
13//!
14//! let cipher = Cipher::aes_256_cbc();
15//! let mut seal = Seal::new(cipher, &[key]).unwrap();
16//!
17//! let secret = b"My secret message";
18//! let mut encrypted = vec![0; secret.len() + cipher.block_size()];
19//!
20//! let mut enc_len = seal.update(secret, &mut encrypted).unwrap();
21//! enc_len += seal.finalize(&mut encrypted[enc_len..]).unwrap();
22//! encrypted.truncate(enc_len);
23//! ```
24use crate::cipher::CipherRef;
25use crate::cipher_ctx::CipherCtx;
26use crate::error::ErrorStack;
27use crate::pkey::{HasPrivate, HasPublic, PKey, PKeyRef};
28use crate::symm::Cipher;
29use foreign_types::ForeignTypeRef;
30
31/// Represents an EVP_Seal context.
32pub struct Seal {
33 ctx: CipherCtx,
34 iv: Option<Vec<u8>>,
35 enc_keys: Vec<Vec<u8>>,
36}
37
38impl Seal {
39 /// Creates a new `Seal`.
40 pub fn new<T>(cipher: Cipher, pub_keys: &[PKey<T>]) -> Result<Seal, ErrorStack>
41 where
42 T: HasPublic,
43 {
44 let mut iv = cipher.iv_len().map(|len| vec![0; len]);
45 let mut enc_keys = vec![vec![]; pub_keys.len()];
46
47 let mut ctx = CipherCtx::new()?;
48 ctx.seal_init(
49 Some(unsafe { CipherRef::from_ptr(cipher.as_ptr() as *mut _) }),
50 pub_keys,
51 &mut enc_keys,
52 iv.as_deref_mut(),
53 )?;
54
55 Ok(Seal { ctx, iv, enc_keys })
56 }
57
58 /// Returns the initialization vector, if the cipher uses one.
59 #[allow(clippy::option_as_ref_deref)]
60 pub fn iv(&self) -> Option<&[u8]> {
61 self.iv.as_ref().map(|v| &**v)
62 }
63
64 /// Returns the encrypted keys.
65 pub fn encrypted_keys(&self) -> &[Vec<u8>] {
66 &self.enc_keys
67 }
68
69 /// Feeds data from `input` through the cipher, writing encrypted bytes into `output`.
70 ///
71 /// The number of bytes written to `output` is returned. Note that this may
72 /// not be equal to the length of `input`.
73 ///
74 /// # Panics
75 ///
76 /// Panics if `output.len() < input.len() + block_size` where `block_size` is
77 /// the block size of the cipher (see `Cipher::block_size`), or if
78 /// `output.len() > c_int::max_value()`.
79 pub fn update(&mut self, input: &[u8], output: &mut [u8]) -> Result<usize, ErrorStack> {
80 self.ctx.cipher_update(input, Some(output))
81 }
82
83 /// Finishes the encryption process, writing any remaining data to `output`.
84 ///
85 /// The number of bytes written to `output` is returned.
86 ///
87 /// `update` should not be called after this method.
88 ///
89 /// # Panics
90 ///
91 /// Panics if `output` is less than the cipher's block size.
92 pub fn finalize(&mut self, output: &mut [u8]) -> Result<usize, ErrorStack> {
93 self.ctx.cipher_final(output)
94 }
95}
96
97/// Represents an EVP_Open context.
98pub struct Open {
99 ctx: CipherCtx,
100}
101
102impl Open {
103 /// Creates a new `Open`.
104 pub fn new<T>(
105 cipher: Cipher,
106 priv_key: &PKeyRef<T>,
107 iv: Option<&[u8]>,
108 encrypted_key: &[u8],
109 ) -> Result<Open, ErrorStack>
110 where
111 T: HasPrivate,
112 {
113 let mut ctx = CipherCtx::new()?;
114 ctx.open_init(
115 Some(unsafe { CipherRef::from_ptr(cipher.as_ptr() as *mut _) }),
116 encrypted_key,
117 iv,
118 Some(priv_key),
119 )?;
120
121 Ok(Open { ctx })
122 }
123
124 /// Feeds data from `input` through the cipher, writing decrypted bytes into `output`.
125 ///
126 /// The number of bytes written to `output` is returned. Note that this may
127 /// not be equal to the length of `input`.
128 ///
129 /// # Panics
130 ///
131 /// Panics if `output.len() < input.len() + block_size` where
132 /// `block_size` is the block size of the cipher (see `Cipher::block_size`),
133 /// or if `output.len() > c_int::max_value()`.
134 pub fn update(&mut self, input: &[u8], output: &mut [u8]) -> Result<usize, ErrorStack> {
135 self.ctx.cipher_update(input, Some(output))
136 }
137
138 /// Finishes the decryption process, writing any remaining data to `output`.
139 ///
140 /// The number of bytes written to `output` is returned.
141 ///
142 /// `update` should not be called after this method.
143 ///
144 /// # Panics
145 ///
146 /// Panics if `output` is less than the cipher's block size.
147 pub fn finalize(&mut self, output: &mut [u8]) -> Result<usize, ErrorStack> {
148 self.ctx.cipher_final(output)
149 }
150}
151
152#[cfg(test)]
153mod test {
154 use super::*;
155 use crate::pkey::PKey;
156 use crate::symm::Cipher;
157
158 #[test]
159 fn public_encrypt_private_decrypt() {
160 let private_pem = include_bytes!("../test/rsa.pem");
161 let public_pem = include_bytes!("../test/rsa.pem.pub");
162 let private_key = PKey::private_key_from_pem(private_pem).unwrap();
163 let public_key = PKey::public_key_from_pem(public_pem).unwrap();
164 let cipher = Cipher::aes_256_cbc();
165 let secret = b"My secret message";
166
167 let mut seal = Seal::new(cipher, &[public_key]).unwrap();
168 let mut encrypted = vec![0; secret.len() + cipher.block_size()];
169 let mut enc_len = seal.update(secret, &mut encrypted).unwrap();
170 enc_len += seal.finalize(&mut encrypted[enc_len..]).unwrap();
171 let iv = seal.iv();
172 let encrypted_key = &seal.encrypted_keys()[0];
173
174 let mut open = Open::new(cipher, &private_key, iv, encrypted_key).unwrap();
175 let mut decrypted = vec![0; enc_len + cipher.block_size()];
176 let mut dec_len = open.update(&encrypted[..enc_len], &mut decrypted).unwrap();
177 dec_len += open.finalize(&mut decrypted[dec_len..]).unwrap();
178
179 assert_eq!(&secret[..], &decrypted[..dec_len]);
180 }
181}
182