1use std::io::Cursor;
4
5use anyhow::Result;
6use mail_builder::mime::MimePart;
7
8use crate::aheader::{Aheader, EncryptPreference};
9use crate::context::Context;
10use crate::key::{SignedPublicKey, load_self_public_key, load_self_secret_key};
11use crate::pgp::{self, SeipdVersion};
12
13#[derive(Debug)]
14pub struct EncryptHelper {
15 pub prefer_encrypt: EncryptPreference,
16 pub addr: String,
17 pub public_key: SignedPublicKey,
18}
19
20impl EncryptHelper {
21 pub async fn new(context: &Context) -> Result<EncryptHelper> {
22 let prefer_encrypt = EncryptPreference::Mutual;
23 let addr = context.get_primary_self_addr().await?;
24 let public_key = load_self_public_key(context).await?;
25
26 Ok(EncryptHelper {
27 prefer_encrypt,
28 addr,
29 public_key,
30 })
31 }
32
33 pub fn get_aheader(&self) -> Aheader {
34 Aheader {
35 addr: self.addr.clone(),
36 public_key: self.public_key.clone(),
37 prefer_encrypt: self.prefer_encrypt,
38 verified: false,
39 }
40 }
41
42 pub async fn encrypt(
44 self,
45 context: &Context,
46 keyring: Vec<SignedPublicKey>,
47 mail_to_encrypt: MimePart<'static>,
48 compress: bool,
49 anonymous_recipients: bool,
50 seipd_version: SeipdVersion,
51 ) -> Result<String> {
52 let sign_key = load_self_secret_key(context).await?;
53
54 let mut raw_message = Vec::new();
55 let cursor = Cursor::new(&mut raw_message);
56 mail_to_encrypt.clone().write_part(cursor).ok();
57
58 let ctext = pgp::pk_encrypt(
59 raw_message,
60 keyring,
61 sign_key,
62 compress,
63 anonymous_recipients,
64 seipd_version,
65 )
66 .await?;
67
68 Ok(ctext)
69 }
70
71 pub async fn encrypt_symmetrically(
74 self,
75 context: &Context,
76 shared_secret: &str,
77 mail_to_encrypt: MimePart<'static>,
78 compress: bool,
79 ) -> Result<String> {
80 let sign_key = load_self_secret_key(context).await?;
81
82 let mut raw_message = Vec::new();
83 let cursor = Cursor::new(&mut raw_message);
84 mail_to_encrypt.clone().write_part(cursor).ok();
85
86 let ctext =
87 pgp::symm_encrypt_message(raw_message, sign_key, shared_secret, compress).await?;
88
89 Ok(ctext)
90 }
91
92 pub async fn sign(self, context: &Context, mail: &MimePart<'static>) -> Result<String> {
95 let sign_key = load_self_secret_key(context).await?;
96 let mut buffer = Vec::new();
97 mail.clone().write_part(&mut buffer)?;
98 let signature = pgp::pk_calc_signature(buffer, &sign_key)?;
99 Ok(signature)
100 }
101}
102
103pub async fn ensure_secret_key_exists(context: &Context) -> Result<()> {
111 load_self_public_key(context).await?;
112 Ok(())
113}
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118 use crate::chat::send_text_msg;
119 use crate::config::Config;
120 use crate::message::Message;
121 use crate::receive_imf::receive_imf;
122 use crate::test_utils::{TestContext, TestContextManager};
123
124 mod ensure_secret_key_exists {
125 use super::*;
126
127 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
128 async fn test_prexisting() {
129 let t = TestContext::new_alice().await;
130 assert!(ensure_secret_key_exists(&t).await.is_ok());
131 }
132
133 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
134 async fn test_not_configured() {
135 let t = TestContext::new().await;
136 assert!(ensure_secret_key_exists(&t).await.is_err());
137 }
138 }
139
140 #[test]
141 fn test_mailmime_parse() {
142 let plain = b"Chat-Disposition-Notification-To: hello@world.de
143Chat-Group-ID: CovhGgau8M-
144Chat-Group-Name: Delta Chat Dev
145Subject: =?utf-8?Q?Chat=3A?= Delta Chat =?utf-8?Q?Dev=3A?= sidenote for
146 =?utf-8?Q?all=3A?= rust core master ...
147Content-Type: text/plain; charset=\"utf-8\"; protected-headers=\"v1\"
148Content-Transfer-Encoding: quoted-printable
149
150sidenote for all: things are trick atm recomm=
151end not to try to run with desktop or ios unless you are ready to hunt bugs
152
153-- =20
154Sent with my Delta Chat Messenger: https://delta.chat";
155 let mail = mailparse::parse_mail(plain).expect("failed to parse valid message");
156
157 assert_eq!(mail.headers.len(), 6);
158 assert!(
159 mail.get_body().unwrap().starts_with(
160 "sidenote for all: things are trick atm recommend not to try to run with desktop or ios unless you are ready to hunt bugs")
161 );
162 }
163
164 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
165 async fn test_chatmail_can_send_unencrypted() -> Result<()> {
166 let mut tcm = TestContextManager::new();
167 let bob = &tcm.bob().await;
168 bob.set_config_bool(Config::IsChatmail, true).await?;
169 let bob_chat_id = receive_imf(
170 bob,
171 b"From: alice@example.org\n\
172 To: bob@example.net\n\
173 Message-ID: <2222@example.org>\n\
174 Date: Sun, 22 Mar 3000 22:37:58 +0000\n\
175 \n\
176 Hello\n",
177 false,
178 )
179 .await?
180 .unwrap()
181 .chat_id;
182 bob_chat_id.accept(bob).await?;
183 send_text_msg(bob, bob_chat_id, "hi".to_string()).await?;
184 let sent_msg = bob.pop_sent_msg().await;
185 let msg = Message::load_from_db(bob, sent_msg.sender_msg_id).await?;
186 assert!(!msg.get_showpadlock());
187 Ok(())
188 }
189}