miden_crypto/ies/
message.rs

1use alloc::vec::Vec;
2use core::convert::TryFrom;
3
4use super::{IesScheme, keys::EphemeralPublicKey};
5use crate::utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable};
6
7// SEALED MESSAGE
8// ================================================================================================
9
10/// A sealed message containing encrypted data
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct SealedMessage {
13    /// Ephemeral public key (determines scheme and provides key material)
14    pub(super) ephemeral_key: EphemeralPublicKey,
15    /// Encrypted ciphertext with authentication tag and nonce
16    pub(super) ciphertext: Vec<u8>,
17}
18
19impl SealedMessage {
20    /// Returns the scheme used to create this sealed message.
21    pub(super) fn scheme(&self) -> IesScheme {
22        self.ephemeral_key.scheme()
23    }
24
25    /// Returns the scheme name used to create this sealed message.
26    pub fn scheme_name(&self) -> &'static str {
27        self.scheme().name()
28    }
29
30    /// Returns the byte representation of this sealed message.
31    pub fn to_bytes(&self) -> Vec<u8> {
32        <Self as Serializable>::to_bytes(self)
33    }
34}
35
36impl Serializable for SealedMessage {
37    fn write_into<W: ByteWriter>(&self, target: &mut W) {
38        let scheme = self.scheme();
39        target.write_u8(scheme as u8);
40
41        self.ephemeral_key.to_bytes().write_into(target);
42        self.ciphertext.write_into(target);
43    }
44}
45
46impl Deserializable for SealedMessage {
47    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
48        let scheme = match IesScheme::try_from(source.read_u8()?) {
49            Ok(a) => a,
50            Err(_) => {
51                return Err(DeserializationError::InvalidValue("Unsupported scheme".into()));
52            },
53        };
54
55        let eph_key_bytes = Vec::<u8>::read_from(source)?;
56        let ephemeral_key =
57            EphemeralPublicKey::from_bytes(scheme, &eph_key_bytes).map_err(|e| {
58                DeserializationError::InvalidValue(format!("Invalid ephemeral key: {e}"))
59            })?;
60
61        let ciphertext = Vec::<u8>::read_from(source)?;
62
63        Ok(Self { ephemeral_key, ciphertext })
64    }
65}