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