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;
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 ) -> Result<String> {
51 let sign_key = load_self_secret_key(context).await?;
52
53 let mut raw_message = Vec::new();
54 let cursor = Cursor::new(&mut raw_message);
55 mail_to_encrypt.clone().write_part(cursor).ok();
56
57 let ctext = pgp::pk_encrypt(
58 raw_message,
59 keyring,
60 Some(sign_key),
61 compress,
62 anonymous_recipients,
63 )
64 .await?;
65
66 Ok(ctext)
67 }
68
69 pub async fn encrypt_symmetrically(
72 self,
73 context: &Context,
74 shared_secret: &str,
75 mail_to_encrypt: MimePart<'static>,
76 compress: bool,
77 ) -> Result<String> {
78 let sign_key = load_self_secret_key(context).await?;
79
80 let mut raw_message = Vec::new();
81 let cursor = Cursor::new(&mut raw_message);
82 mail_to_encrypt.clone().write_part(cursor).ok();
83
84 let ctext =
85 pgp::symm_encrypt_message(raw_message, sign_key, shared_secret, compress).await?;
86
87 Ok(ctext)
88 }
89
90 pub async fn sign(self, context: &Context, mail: &MimePart<'static>) -> Result<String> {
93 let sign_key = load_self_secret_key(context).await?;
94 let mut buffer = Vec::new();
95 mail.clone().write_part(&mut buffer)?;
96 let signature = pgp::pk_calc_signature(buffer, &sign_key)?;
97 Ok(signature)
98 }
99}
100
101pub async fn ensure_secret_key_exists(context: &Context) -> Result<()> {
109 load_self_public_key(context).await?;
110 Ok(())
111}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116 use crate::chat::send_text_msg;
117 use crate::config::Config;
118 use crate::message::Message;
119 use crate::receive_imf::receive_imf;
120 use crate::test_utils::{TestContext, TestContextManager};
121
122 mod ensure_secret_key_exists {
123 use super::*;
124
125 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
126 async fn test_prexisting() {
127 let t = TestContext::new_alice().await;
128 assert!(ensure_secret_key_exists(&t).await.is_ok());
129 }
130
131 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
132 async fn test_not_configured() {
133 let t = TestContext::new().await;
134 assert!(ensure_secret_key_exists(&t).await.is_err());
135 }
136 }
137
138 #[test]
139 fn test_mailmime_parse() {
140 let plain = b"Chat-Disposition-Notification-To: hello@world.de
141Chat-Group-ID: CovhGgau8M-
142Chat-Group-Name: Delta Chat Dev
143Subject: =?utf-8?Q?Chat=3A?= Delta Chat =?utf-8?Q?Dev=3A?= sidenote for
144 =?utf-8?Q?all=3A?= rust core master ...
145Content-Type: text/plain; charset=\"utf-8\"; protected-headers=\"v1\"
146Content-Transfer-Encoding: quoted-printable
147
148sidenote for all: things are trick atm recomm=
149end not to try to run with desktop or ios unless you are ready to hunt bugs
150
151-- =20
152Sent with my Delta Chat Messenger: https://delta.chat";
153 let mail = mailparse::parse_mail(plain).expect("failed to parse valid message");
154
155 assert_eq!(mail.headers.len(), 6);
156 assert!(
157 mail.get_body().unwrap().starts_with(
158 "sidenote for all: things are trick atm recommend not to try to run with desktop or ios unless you are ready to hunt bugs")
159 );
160 }
161
162 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
163 async fn test_chatmail_can_send_unencrypted() -> Result<()> {
164 let mut tcm = TestContextManager::new();
165 let bob = &tcm.bob().await;
166 bob.set_config_bool(Config::IsChatmail, true).await?;
167 let bob_chat_id = receive_imf(
168 bob,
169 b"From: alice@example.org\n\
170 To: bob@example.net\n\
171 Message-ID: <2222@example.org>\n\
172 Date: Sun, 22 Mar 3000 22:37:58 +0000\n\
173 \n\
174 Hello\n",
175 false,
176 )
177 .await?
178 .unwrap()
179 .chat_id;
180 bob_chat_id.accept(bob).await?;
181 send_text_msg(bob, bob_chat_id, "hi".to_string()).await?;
182 let sent_msg = bob.pop_sent_msg().await;
183 let msg = Message::load_from_db(bob, sent_msg.sender_msg_id).await?;
184 assert!(!msg.get_showpadlock());
185 Ok(())
186 }
187}