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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
pub mod backend;
pub mod proto;
pub mod recipients;
pub mod store;
pub mod util;
use std::collections::HashMap;
use std::fmt;
use std::fs;
use std::path::Path;
use anyhow::Result;
use thiserror::Error;
use crate::{Ciphertext, Plaintext, Recipients};
pub const PROTO: Proto = Proto::Gpg;
#[non_exhaustive]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum Proto {
Gpg,
}
impl Proto {
pub fn name(&self) -> &str {
match self {
Self::Gpg => "GPG",
}
}
}
#[derive(Clone, PartialEq)]
#[non_exhaustive]
pub enum Key {
#[cfg(feature = "_crypto-gpg")]
Gpg(proto::gpg::Key),
}
impl Key {
pub fn proto(&self) -> Proto {
match self {
#[cfg(feature = "_crypto-gpg")]
Key::Gpg(_) => Proto::Gpg,
}
}
pub fn fingerprint(&self, short: bool) -> String {
match self {
#[cfg(feature = "_crypto-gpg")]
Key::Gpg(key) => key.fingerprint(short),
}
}
pub fn display(&self) -> String {
match self {
#[cfg(feature = "_crypto-gpg")]
Key::Gpg(key) => key.display_user(),
}
}
}
impl fmt::Display for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"[{}] {} - {}",
self.proto().name(),
self.fingerprint(true),
self.display(),
)
}
}
#[allow(unreachable_code)]
pub fn context(proto: Proto) -> Result<Context, Err> {
match proto {
Proto::Gpg => {
#[cfg(feature = "backend-gpgme")]
return Ok(Context::from(Box::new(
backend::gpgme::context::context().map_err(|err| Err::Context(err.into()))?,
)));
#[cfg(feature = "backend-gnupg-bin")]
return Ok(Context::from(Box::new(
backend::gnupg_bin::context::context().map_err(|err| Err::Context(err.into()))?,
)));
}
}
Err(Err::Unsupported(proto))
}
pub struct Context {
context: Box<dyn IsContext>,
}
impl Context {
pub fn from(context: Box<dyn IsContext>) -> Self {
Self { context }
}
}
impl IsContext for Context {
fn encrypt(&mut self, recipients: &Recipients, plaintext: Plaintext) -> Result<Ciphertext> {
self.context.encrypt(recipients, plaintext)
}
fn decrypt(&mut self, ciphertext: Ciphertext) -> Result<Plaintext> {
self.context.decrypt(ciphertext)
}
fn can_decrypt(&mut self, ciphertext: Ciphertext) -> Result<bool> {
self.context.can_decrypt(ciphertext)
}
fn keys_public(&mut self) -> Result<Vec<Key>> {
self.context.keys_public()
}
fn keys_private(&mut self) -> Result<Vec<Key>> {
self.context.keys_private()
}
fn import_key(&mut self, key: &[u8]) -> Result<()> {
self.context.import_key(key)
}
fn export_key(&mut self, key: Key) -> Result<Vec<u8>> {
self.context.export_key(key)
}
fn supports_proto(&self, proto: Proto) -> bool {
self.context.supports_proto(proto)
}
}
pub trait IsContext {
fn encrypt(&mut self, recipients: &Recipients, plaintext: Plaintext) -> Result<Ciphertext>;
fn encrypt_file(
&mut self,
recipients: &Recipients,
plaintext: Plaintext,
path: &Path,
) -> Result<()> {
fs::write(path, self.encrypt(recipients, plaintext)?.unsecure_ref())
.map_err(|err| Err::WriteFile(err).into())
}
fn decrypt(&mut self, ciphertext: Ciphertext) -> Result<Plaintext>;
fn decrypt_file(&mut self, path: &Path) -> Result<Plaintext> {
self.decrypt(fs::read(path).map_err(Err::ReadFile)?.into())
}
fn can_decrypt(&mut self, ciphertext: Ciphertext) -> Result<bool>;
fn can_decrypt_file(&mut self, path: &Path) -> Result<bool> {
self.can_decrypt(fs::read(path).map_err(Err::ReadFile)?.into())
}
fn keys_public(&mut self) -> Result<Vec<Key>>;
fn keys_private(&mut self) -> Result<Vec<Key>>;
fn get_public_key(&mut self, fingerprint: &str) -> Result<Key> {
self.keys_public()?
.into_iter()
.find(|key| util::fingerprints_equal(key.fingerprint(false), fingerprint))
.ok_or_else(|| Err::UnknownFingerprint.into())
}
fn find_public_keys(&mut self, fingerprints: &[&str]) -> Result<Vec<Key>> {
let keys = self.keys_public()?;
Ok(fingerprints
.into_iter()
.filter_map(|fingerprint| {
keys.iter()
.find(|key| util::fingerprints_equal(key.fingerprint(false), fingerprint))
.cloned()
})
.collect())
}
fn import_key(&mut self, key: &[u8]) -> Result<()>;
fn import_key_file(&mut self, path: &Path) -> Result<()> {
self.import_key(&fs::read(path).map_err(Err::ReadFile)?)
}
fn export_key(&mut self, key: Key) -> Result<Vec<u8>>;
fn export_key_file(&mut self, key: Key, path: &Path) -> Result<()> {
fs::write(path, self.export_key(key)?).map_err(|err| Err::WriteFile(err).into())
}
fn supports_proto(&self, proto: Proto) -> bool;
}
pub struct ContextPool {
contexts: HashMap<Proto, Context>,
}
impl ContextPool {
pub fn empty() -> Self {
Self {
contexts: HashMap::new(),
}
}
pub fn get_mut<'a>(&'a mut self, proto: Proto) -> Result<&'a mut Context> {
Ok(self.contexts.entry(proto).or_insert(context(proto)?))
}
}
#[derive(Debug, Error)]
pub enum Err {
#[error("failed to obtain GPGME cryptography context")]
Context(#[source] anyhow::Error),
#[error("failed to built context, protocol not supportd: {:?}", _0)]
Unsupported(Proto),
#[error("failed to write to file")]
WriteFile(#[source] std::io::Error),
#[error("failed to read from file")]
ReadFile(#[source] std::io::Error),
#[error("fingerprint does not match public key in keychain")]
UnknownFingerprint,
}
pub mod prelude {
pub use super::{store::StoreRecipients, IsContext};
}