Skip to main content

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///
12/// For untrusted encodings, use [`Deserializable::read_from_bytes_with_budget`] with an
13/// application-chosen size limit. This method permits trailing bytes. To require exactly one sealed
14/// message, first reject inputs longer than the size limit. Then decode using
15/// [`Deserializable::read_from`] through a [`BudgetedReader`](crate::utils::BudgetedReader) over a
16/// [`SliceReader`](crate::utils::SliceReader) with the budget set to the input length, and reject
17/// remaining bytes using [`ByteReader::has_more_bytes`]. With a smaller budget, trailing bytes can
18/// go undetected because the reader reports no remaining bytes once its budget is exhausted.
19#[derive(Debug, Clone, PartialEq, Eq)]
20#[cfg_attr(
21    all(feature = "arbitrary", test),
22    miden_test_serialization_macros::serialization_test
23)]
24pub struct SealedMessage {
25    /// Ephemeral public key (determines scheme and provides key material)
26    pub(super) ephemeral_key: EphemeralPublicKey,
27    /// Scheme-specific ciphertext encoding, including its authentication tag.
28    pub(super) ciphertext: Vec<u8>,
29}
30
31impl SealedMessage {
32    /// Returns the scheme used to create this sealed message.
33    pub(super) fn scheme(&self) -> IesScheme {
34        self.ephemeral_key.scheme()
35    }
36
37    /// Returns the scheme name used to create this sealed message.
38    pub fn scheme_name(&self) -> &'static str {
39        self.scheme().name()
40    }
41
42    /// Returns the byte representation of this sealed message.
43    pub fn to_bytes(&self) -> Vec<u8> {
44        <Self as Serializable>::to_bytes(self)
45    }
46}
47
48#[cfg(any(test, feature = "arbitrary"))]
49mod sealed_message_arbitrary {
50    use proptest::prelude::*;
51
52    use super::SealedMessage;
53    use crate::ies::keys::EphemeralPublicKey;
54
55    impl Arbitrary for SealedMessage {
56        type Parameters = ();
57        type Strategy = BoxedStrategy<Self>;
58
59        fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
60            // The reader re-parses the ephemeral key under the scheme byte, so use a valid
61            // key (its own covered strategy); the ciphertext payload is any-valid bytes.
62            (any::<EphemeralPublicKey>(), proptest::collection::vec(any::<u8>(), 0..=32))
63                .prop_map(|(ephemeral_key, ciphertext)| Self { ephemeral_key, ciphertext })
64                .boxed()
65        }
66    }
67}
68
69impl Serializable for SealedMessage {
70    fn write_into<W: ByteWriter>(&self, target: &mut W) {
71        let scheme = self.scheme();
72        target.write_u8(scheme as u8);
73
74        self.ephemeral_key.to_bytes().write_into(target);
75        self.ciphertext.write_into(target);
76    }
77}
78
79impl Deserializable for SealedMessage {
80    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
81        let scheme = match IesScheme::try_from(source.read_u8()?) {
82            Ok(a) => a,
83            Err(_) => {
84                return Err(DeserializationError::InvalidValue("Unsupported scheme".into()));
85            },
86        };
87
88        let eph_key_bytes = Vec::<u8>::read_from(source)?;
89        let ephemeral_key =
90            EphemeralPublicKey::from_bytes(scheme, &eph_key_bytes).map_err(|e| {
91                DeserializationError::InvalidValue(format!("Invalid ephemeral key: {e}"))
92            })?;
93
94        let ciphertext = Vec::<u8>::read_from(source)?;
95
96        Ok(Self { ephemeral_key, ciphertext })
97    }
98}