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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
pub mod error;
pub mod key;
use core::marker::PhantomData;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use crate::error::Error;
use crate::key::{PrivateKey, PublicKey};
pub type Result<T> = std::result::Result<T, Error>;
pub trait ToSeal {
fn seal(self) -> Result<(PrivateKey, Package<Self>)>;
}
pub trait ToSealRef {
fn seal(&self) -> Result<(PrivateKey, Package<Self>)>;
}
pub trait ToSealWithKey {
fn seal(self, private_key: &PrivateKey) -> Result<Package<Self>>;
}
pub trait ToSealRefWithKey {
fn seal(&self, private_key: &PrivateKey) -> Result<Package<Self>>;
}
pub trait ToSealWithSharedKey {
fn seal(self, private_key: &PrivateKey, public_key: Vec<PublicKey>) -> Result<Package<Self>>;
}
pub trait ToSealRefWithSharedKey {
fn seal(&self, private_key: &PrivateKey, public_key: Vec<PublicKey>) -> Result<Package<Self>>;
}
pub trait ToOpen<T> {
fn open(&self, key: &PrivateKey) -> Result<T>;
}
pub trait ToOpenWithPublicKey<T> {
fn open(&self, key: &PrivateKey) -> Result<T>;
}
pub trait ToOpenWithSharedKey<T> {
fn open(&self, key: &PrivateKey, public_key: &PublicKey) -> Result<T>;
}
#[derive(Default, Deserialize, Serialize, Clone, PartialEq, Eq, Debug)]
pub struct Package<T: ?Sized> {
data: Vec<Vec<u8>>,
#[serde(skip_serializing_if = "Vec::is_empty")]
signature: Vec<u8>,
#[serde(skip_serializing_if = "Option::is_none")]
public_key: Option<PublicKey>,
#[serde(skip_serializing_if = "Option::is_none")]
recipients: Option<Vec<PublicKey>>,
#[serde(skip_serializing, skip_deserializing)]
marker: PhantomData<T>,
}
impl<T> Package<T>
where
T: Serialize + DeserializeOwned + Clone,
{
pub fn import(
data: Vec<Vec<u8>>,
public_key: Option<PublicKey>,
recipients: Option<Vec<PublicKey>>,
signature: Option<Vec<u8>>,
) -> Self {
let signature = signature.unwrap_or_default();
Self {
data,
signature,
public_key,
recipients,
marker: PhantomData,
}
}
pub fn deserialize(data: &str) -> Result<Self> {
serde_json::from_str(data).map_err(Error::from)
}
pub fn serialize(&self) -> Result<String> {
serde_json::to_string(self).map_err(Error::from)
}
pub fn from_slice<A: AsRef<[u8]>>(data: A) -> Result<Self> {
serde_json::from_slice(data.as_ref()).map_err(Error::from)
}
pub fn to_vec(&self) -> Result<Vec<u8>> {
serde_json::to_vec(self).map_err(Error::from)
}
}
impl<T> Package<T> {
pub fn has_recipient(&self, public_key: &PublicKey) -> bool {
if let Ok(list) = self.recipients() {
return list.contains(public_key);
}
false
}
pub fn recipients(&self) -> Result<&[PublicKey]> {
self.recipients
.as_deref()
.ok_or(Error::RecipientsNotAvailable)
}
}
impl<T> ToSeal for T
where
T: Serialize + Default,
{
fn seal(self) -> Result<(PrivateKey, Package<T>)> {
ToSealRef::seal(&self)
}
}
impl<T> ToSealRef for T
where
T: Serialize + Default,
{
fn seal(&self) -> Result<(PrivateKey, Package<T>)> {
let private_key = PrivateKey::new();
let package = ToSealRefWithKey::seal(self, &private_key)?;
Ok((private_key, package))
}
}
impl<T> ToSealWithKey for T
where
T: Serialize + Default,
{
fn seal(self, private_key: &PrivateKey) -> Result<Package<T>> {
ToSealRefWithKey::seal(&self, private_key)
}
}
impl<T> ToSealRefWithKey for T
where
T: Serialize + Default,
{
fn seal(&self, private_key: &PrivateKey) -> Result<Package<T>> {
let mut package = Package::default();
let inner_data = serde_json::to_vec(self)?;
package.signature = private_key.sign(&inner_data)?;
package.data = vec![private_key.encrypt(&inner_data, None)?];
if let Ok(public_key) = private_key.public_key() {
package.public_key = Some(public_key)
}
Ok(package)
}
}
impl<T> ToSealWithSharedKey for T
where
T: Serialize + Default,
{
fn seal(self, private_key: &PrivateKey, public_key: Vec<PublicKey>) -> Result<Package<T>> {
ToSealRefWithSharedKey::seal(&self, private_key, public_key)
}
}
impl<T> ToSealRefWithSharedKey for T
where
T: Serialize + Default,
{
fn seal(&self, private_key: &PrivateKey, public_key: Vec<PublicKey>) -> Result<Package<T>> {
let mut package = Package::default();
let inner_data = serde_json::to_vec(self)?;
let sig = private_key.sign(&inner_data)?;
let ptype = private_key.public_key()?.key_type();
package.signature = sig;
package.data = public_key
.iter()
.filter(|public_key| public_key.key_type() == ptype)
.filter_map(|public_key| {
private_key
.encrypt(&inner_data, Some(public_key.clone()))
.ok()
})
.collect::<Vec<_>>();
package.recipients = Some(public_key);
package.public_key = Some(private_key.public_key()?);
Ok(package)
}
}
impl<T> ToOpen<T> for Package<T>
where
T: DeserializeOwned,
{
fn open(&self, key: &PrivateKey) -> Result<T> {
let data = self.data.first().ok_or(Error::InvalidPackage)?;
let data = key.decrypt(data, None)?;
key.verify(&data, &self.signature)?;
serde_json::from_slice(&data).map_err(Error::from)
}
}
impl<T> ToOpenWithPublicKey<T> for Package<T>
where
T: DeserializeOwned,
{
fn open(&self, key: &PrivateKey) -> Result<T> {
if !self.has_recipient(&key.public_key()?) {
return Err(Error::InvalidPublickey);
}
let pk = self.public_key.as_ref().ok_or(Error::InvalidPublickey)?;
for data in &self.data {
if let Ok(data) = key.decrypt(data, Some(pk.clone())) {
pk.verify(&data, &self.signature)?;
return serde_json::from_slice(&data).map_err(Error::from);
}
}
Err(Error::DecryptionError)
}
}