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
use crate::{
error::Error,
key::combined_key::{ReceiverCombinedKey, SenderCombinedKey},
msg::EncryptedMessage,
};
use crypto_box::{
aead::{Aead, Payload},
ChaChaBox,
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use super::{
impl_detail::{self, nonce::generate_nonce},
SerializedPlain,
};
pub trait SerdeEncryptPublicKey {
fn encrypt(&self, combined_key: &SenderCombinedKey) -> Result<EncryptedMessage, Error>
where
Self: Serialize,
{
let nonce = generate_nonce();
let sender_box = ChaChaBox::new(
combined_key.receiver_public_key().as_ref(),
combined_key.sender_private_key().as_ref(),
);
let serial_plain = impl_detail::serialize(&self)?;
let aad = b"".as_ref();
let encrypted = sender_box
.encrypt(
&nonce,
Payload {
msg: &serial_plain,
aad,
},
)
.map_err(|_| {
Error::encryption_error("failed to encrypt serialized data into ChaChaBox")
})?;
Ok(EncryptedMessage::new(encrypted, nonce.into()))
}
fn decrypt_owned(
encrypted_message: &EncryptedMessage,
combined_key: &ReceiverCombinedKey,
) -> Result<Self, Error>
where
Self: Sized + DeserializeOwned,
{
let serial_plain = Self::decrypt_ref(encrypted_message, combined_key)?;
serial_plain.deserialize()
}
fn decrypt_ref<'de>(
encrypted_message: &EncryptedMessage,
combined_key: &ReceiverCombinedKey,
) -> Result<SerializedPlain<Self>, Error>
where
Self: Sized + Deserialize<'de>,
{
let receiver_box = ChaChaBox::new(
combined_key.sender_public_key().as_ref(),
combined_key.receiver_private_key().as_ref(),
);
let nonce = encrypted_message.nonce();
let encrypted = encrypted_message.encrypted();
let serial_plain = receiver_box
.decrypt(nonce.into(), encrypted)
.map_err(|_| Error::decryption_error("error on decryption of ChaChaBox"))?;
Ok(SerializedPlain::new(serial_plain))
}
}