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
use anyhow::Result;
use gpgme::{Context, EncryptFlags, Key};
use thiserror::Error;
use zeroize::Zeroize;
use crate::{Ciphertext, Plaintext};
const ENCRYPT_FLAGS: EncryptFlags = EncryptFlags::ALWAYS_TRUST;
pub fn encrypt(
context: &mut Context,
recipients: &[&str],
plaintext: Plaintext,
) -> Result<Ciphertext> {
assert!(
!recipients.is_empty(),
"attempting to encrypt secret for empty list of recipients"
);
let mut ciphertext = vec![];
let keys = fingerprints_to_keys(context, recipients)?;
context
.encrypt_with_flags(
keys.iter(),
plaintext.unsecure_ref(),
&mut ciphertext,
ENCRYPT_FLAGS,
)
.map_err(Err::Encrypt)?;
Ok(Ciphertext::from(ciphertext))
}
pub fn decrypt(context: &mut Context, ciphertext: Ciphertext) -> Result<Plaintext> {
let mut plaintext = vec![];
context
.decrypt(ciphertext.unsecure_ref(), &mut plaintext)
.map_err(Err::Decrypt)?;
Ok(Plaintext::from(plaintext))
}
pub fn can_decrypt(context: &mut Context, ciphertext: Ciphertext) -> Result<bool> {
let mut plaintext = vec![];
let result = context.decrypt(ciphertext.unsecure_ref(), &mut plaintext);
plaintext.zeroize();
match result {
Ok(_) => Ok(true),
Err(err) if gpgme::error::Error::NO_SECKEY.code() == err.code() => Ok(false),
Err(_) => Ok(true),
}
}
pub fn public_keys(context: &mut Context) -> Result<Vec<KeyId>> {
Ok(context
.keys()?
.into_iter()
.filter_map(|k| k.ok())
.filter(|k| k.can_encrypt())
.map(|k| k.into())
.collect())
}
pub fn private_keys(context: &mut Context) -> Result<Vec<KeyId>> {
Ok(context
.secret_keys()?
.into_iter()
.filter_map(|k| k.ok())
.filter(|k| k.can_encrypt())
.map(|k| k.into())
.collect())
}
pub fn import_key(context: &mut Context, key: &[u8]) -> Result<()> {
let key_str = std::str::from_utf8(&key).expect("exported key is invalid UTF-8");
assert!(
!key_str.contains("PRIVATE KEY"),
"imported key contains PRIVATE KEY, blocked to prevent accidentally leaked secret key"
);
assert!(
key_str.contains("PUBLIC KEY"),
"imported key must contain PUBLIC KEY, blocked to prevent accidentally leaked secret key"
);
context
.import(key)
.map(|_| ())
.map_err(|err| Err::Import(err.into()).into())
}
pub fn export_key(context: &mut Context, fingerprint: &str) -> Result<Vec<u8>> {
let key = context
.get_key(fingerprint)
.map_err(|err| Err::Export(Err::UnknownFingerprint(err).into()))?;
let mut data: Vec<u8> = vec![];
let armor = context.armor();
context.set_armor(true);
context.export_keys(&[key], gpgme::ExportMode::empty(), &mut data)?;
context.set_armor(armor);
let data_str = std::str::from_utf8(&data).expect("exported key is invalid UTF-8");
assert!(
!data_str.contains("PRIVATE KEY"),
"exported key contains PRIVATE KEY, blocked to prevent accidentally leaking secret key"
);
assert!(
data_str.contains("PUBLIC KEY"),
"exported key must contain PUBLIC KEY, blocked to prevent accidentally leaking secret key"
);
Ok(data)
}
#[derive(Clone)]
pub struct KeyId(pub String, pub Vec<String>);
impl From<Key> for KeyId {
fn from(key: Key) -> Self {
Self(
key.fingerprint()
.expect("GPGME key does not have fingerprint")
.to_string(),
key.user_ids()
.map(|user| {
let mut parts = vec![];
if let Ok(name) = user.name() {
if !name.trim().is_empty() {
parts.push(name.into());
}
}
if let Ok(comment) = user.comment() {
if !comment.trim().is_empty() {
parts.push(format!("({})", comment));
}
}
if let Ok(email) = user.email() {
if !email.trim().is_empty() {
parts.push(format!("<{}>", email));
}
}
parts.join(" ")
})
.collect(),
)
}
}
fn fingerprints_to_keys(context: &mut Context, fingerprints: &[&str]) -> Result<Vec<Key>> {
let mut keys = vec![];
for fp in fingerprints {
keys.push(
context
.get_key(fp.to_owned())
.map_err(Err::UnknownFingerprint)?,
);
}
Ok(keys)
}
#[derive(Debug, Error)]
pub enum Err {
#[error("failed to obtain GPGME cryptography context")]
Context(#[source] gpgme::Error),
#[error("failed to encrypt plaintext")]
Encrypt(#[source] gpgme::Error),
#[error("failed to decrypt ciphertext")]
Decrypt(#[source] gpgme::Error),
#[error("failed to import key")]
Import(#[source] anyhow::Error),
#[error("failed to export key")]
Export(#[source] anyhow::Error),
#[error("fingerprint does not match public key in keychain")]
UnknownFingerprint(#[source] gpgme::Error),
}