use alloc::boxed::Box;
use alloc::string::String;
use serde::{Deserialize, Serialize};
use umbral_pre::{
decrypt_original, decrypt_reencrypted, encrypt, serde_bytes, Capsule, DecryptionError,
EncryptionError, PublicKey, ReencryptionError, SecretKey, VerifiedCapsuleFrag,
};
use crate::conditions::Conditions;
use crate::versioning::{
messagepack_deserialize, messagepack_serialize, ProtocolObject, ProtocolObjectInner,
};
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
pub struct MessageKit {
pub capsule: Capsule,
#[serde(with = "serde_bytes::as_base64")]
ciphertext: Box<[u8]>,
pub conditions: Option<Conditions>,
}
impl MessageKit {
pub fn new(
policy_encrypting_key: &PublicKey,
plaintext: &[u8],
conditions: Option<&Conditions>,
) -> Self {
let (capsule, ciphertext) = match encrypt(policy_encrypting_key, plaintext) {
Ok(result) => result,
Err(err) => match err {
EncryptionError::PlaintextTooLarge => panic!("encryption failed - out of memory?"),
},
};
Self {
capsule,
ciphertext,
conditions: conditions.cloned(),
}
}
pub fn decrypt(&self, sk: &SecretKey) -> Result<Box<[u8]>, DecryptionError> {
decrypt_original(sk, &self.capsule, &self.ciphertext)
}
pub fn decrypt_reencrypted(
&self,
sk: &SecretKey,
policy_encrypting_key: &PublicKey,
vcfrags: impl IntoIterator<Item = VerifiedCapsuleFrag>,
) -> Result<Box<[u8]>, ReencryptionError> {
decrypt_reencrypted(
sk,
policy_encrypting_key,
&self.capsule,
vcfrags,
self.ciphertext.clone(),
)
}
}
impl<'a> ProtocolObjectInner<'a> for MessageKit {
fn brand() -> [u8; 4] {
*b"MKit"
}
fn version() -> (u16, u16) {
(3, 0)
}
fn unversioned_to_bytes(&self) -> Box<[u8]> {
messagepack_serialize(&self)
}
fn unversioned_from_bytes(minor_version: u16, bytes: &[u8]) -> Option<Result<Self, String>> {
if minor_version == 0 {
Some(messagepack_deserialize(bytes))
} else {
None
}
}
}
impl<'a> ProtocolObject<'a> for MessageKit {}