1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
use crate::{Envelope, EnvelopeError};
#[cfg(feature = "known_value")]
use crate::extension::known_values;

use bc_components::{SealedMessage, PublicKeyBase, SymmetricKey, Nonce, PrivateKeyBase};
use bytes::Bytes;
use dcbor::prelude::*;

/// Support for public key encryption.
impl Envelope {
    /// Returns a new envelope with an added `hasRecipient: SealedMessage` assertion.
    ///
    /// The `SealedMessage` contains the `contentKey` encrypted to the recipient's `PublicKeyBase`.
    ///
    /// - Parameters:
    ///   - recipient: The `PublicKeyBase` of the recipient.
    ///   - contentKey: The `SymmetricKey` that was used to encrypt the subject.
    ///
    /// - Returns: The new envelope.
    pub fn add_recipient(&self, recipient: &PublicKeyBase, content_key: &SymmetricKey) -> Self {
        self.add_recipient_opt(recipient, content_key, None, None::<&Nonce>)
    }

    #[doc(hidden)]
    pub fn add_recipient_opt(&self, recipient: &PublicKeyBase, content_key: &SymmetricKey, test_key_material: Option<&Bytes>, test_nonce: Option<&Nonce>) -> Self {
        let assertion = Self::make_has_recipient(recipient, content_key, test_key_material, test_nonce);
        self.add_assertion_envelope(assertion).unwrap()
    }

    /// Returns an array of `SealedMessage`s from all of the envelope's `hasRecipient` assertions.
    ///
    /// - Throws: Throws an exception if any `hasRecipient` assertions do not have a `SealedMessage` as their object.
    pub fn recipients(&self) -> anyhow::Result<Vec<SealedMessage>> {
        self
            .assertions_with_predicate(known_values::HAS_RECIPIENT)
            .into_iter()
            .filter(|assertion| {
                !assertion.object().unwrap().is_obscured()
            })
            .map(|assertion| {
                assertion.object().unwrap().extract_subject::<SealedMessage>()
            })
            .collect()
    }

    /// Returns an new envelope with its subject encrypted and a `hasRecipient`
    /// assertion added for each of the `recipients`.
    ///
    /// Generates an ephemeral symmetric key which is used to encrypt the subject and
    /// which is then encrypted to each recipient's public key.
    ///
    /// - Parameter recipients: An array of `PublicKeyBase`, one for each potential
    /// recipient.
    ///
    /// - Returns: The encrypted envelope.
    ///
    /// - Throws: If the envelope is already encrypted.
    #[cfg(feature = "encrypt")]
    pub fn encrypt_subject_to_recipients<T>(
        &self,
        recipients: &[T]
    ) -> Result<Self, EnvelopeError>
    where
        T: AsRef<PublicKeyBase>
    {
        self.encrypt_subject_to_recipients_opt(recipients, None, None::<&Nonce>)
    }

    #[cfg(feature = "encrypt")]
    #[doc(hidden)]
    pub fn encrypt_subject_to_recipients_opt<T>(
        &self,
        recipients: &[T],
        test_key_material: Option<&Bytes>,
        test_nonce: Option<&Nonce>
    ) -> Result<Self, EnvelopeError>
    where
        T: AsRef<PublicKeyBase>
    {
        let content_key = SymmetricKey::new();
        let mut e = self.encrypt_subject(&content_key)?;
        for recipient in recipients {
            e = e.add_recipient_opt(recipient.as_ref(), &content_key, test_key_material, test_nonce);
        }
        Ok(e)
    }

    /// Returns a new envelope with its subject encrypted and a `hasRecipient`
    /// assertion added for the `recipient`.
    ///
    /// Generates an ephemeral symmetric key which is used to encrypt the subject and
    /// which is then encrypted to the recipient's public key.
    ///
    /// - Parameter recipient: The recipient's `PublicKeyBase`.
    ///
    /// - Returns: The encrypted envelope.
    #[cfg(feature = "encrypt")]
    pub fn encrypt_subject_to_recipient(&self, recipient: &PublicKeyBase) -> Result<Self, EnvelopeError> {
        self.encrypt_subject_to_recipient_opt(recipient, None, None::<&Nonce>)
    }

    #[cfg(feature = "encrypt")]
    #[doc(hidden)]
    pub fn encrypt_subject_to_recipient_opt(&self, recipient: &PublicKeyBase, test_key_material: Option<&Bytes>, test_nonce: Option<&Nonce>) -> Result<Self, EnvelopeError> {
        self.encrypt_subject_to_recipients_opt(&[recipient], test_key_material, test_nonce)
    }

    #[cfg(feature = "encrypt")]
    fn first_plaintext_in_sealed_messages(sealed_messages: &[SealedMessage], private_keys: &PrivateKeyBase) -> Result<Vec<u8>, EnvelopeError> {
        for sealed_message in sealed_messages {
            let a = sealed_message.decrypt(private_keys).ok();
            if let Some(plaintext) = a {
                return Ok(plaintext);
            }
        }
        Err(EnvelopeError::InvalidRecipient)
    }

    /// Returns a new envelope with its subject decrypted using the recipient's
    /// `PrivateKeyBase`.
    ///
    /// - Parameter recipient: The recipient's `PrivateKeyBase`
    ///
    /// - Returns: The decryptedEnvelope.
    ///
    /// - Throws: If a `SealedMessage` for `recipient` is not found among the
    /// `hasRecipient` assertions on the envelope.
    #[cfg(feature = "encrypt")]
    pub fn decrypt_to_recipient(&self, recipient: &PrivateKeyBase) -> anyhow::Result<Self> {
        let sealed_messages = self.clone().recipients()?;
        let content_key_data = Self::first_plaintext_in_sealed_messages(&sealed_messages, recipient)?;
        let content_key = SymmetricKey::from_tagged_cbor_data(&content_key_data)?;
        self.decrypt_subject(&content_key)
    }

    /// Convenience constructor for a `hasRecipient: SealedMessage` assertion.
    ///
    /// The `SealedMessage` contains the `contentKey` encrypted to the recipient's `PublicKeyBase`.
    ///
    /// - Parameters:
    ///   - recipient: The `PublicKeyBase` of the recipient.
    ///   - contentKey: The `SymmetricKey` that was used to encrypt the subject.
    ///
    /// - Returns: The assertion envelope.
    fn make_has_recipient(recipient: &PublicKeyBase, content_key: &SymmetricKey, test_key_material: Option<&Bytes>, test_nonce: Option<&Nonce>) -> Self
    {
        let sealed_message = SealedMessage::new_opt(content_key.cbor_data(), recipient, None::<Bytes>, test_key_material.cloned(), test_nonce);
        Self::new_assertion(known_values::HAS_RECIPIENT, sealed_message)
    }
}