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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
//! A library for using cryptoki (PKCS#11) tokens from Sequoia.
//!
//! This library supports the use of cryptographic mechanisms via a
//! [cryptoki (PKCS#11) interface] with Sequoia PGP. The cryptoki
//! interface is usually implemented by a library that interfaces with
//! a hardware token.
//!
//! [cryptoki (PKCS#11) interface]: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.2/pkcs11-spec-v3.2.html
//!
//! This library is specifically not a generic interface to cryptoki
//! tokens. Instead, it assumes that the user wants to use the tokens
//! in an OpenPGP context. For instance, when generating or importing
//! a key, the key's key ID is constructed in such a way that the
//! OpenPGP parameters that cannot be inferred from the information
//! stored on the token are encoded in the key ID. This allows
//! reconstructing the public key packet and consequently the key's
//! OpenPGP fingerprint using just data stored on the token.
//!
//! It is not currently possible to use a key whose key ID does not
//! include the OpenPGP parameters. This means that you can't use a
//! generic tool to generate the key, and then use that key with this
//! library. This is usually a reasonable restriction, as key
//! material should not be shared between different protocols.
//!
//! # Examples
//!
//! ## Iterate Over Keys
//!
//! The following code creates a default context and iterates over the
//! available keys. The configuration file is read from the user's
//! Sequoia home directory and respects the `SEQUOIA_HOME` environment
//! variable. The configuration indicates what cryptoki modules to
//! load.
//!
//! ```
//! use sequoia_cryptoki::Context;
//! # use sequoia_cryptoki::ContextBuilder;
//!
//! # fn main() -> sequoia_openpgp::Result<()> {
//! # if false {
//! let cryptoki = Context::new()?;
//! # }
//! # let cryptoki = ContextBuilder::new().disable_config_file().build()?;
//! for key in cryptoki.keys()? {
//! eprintln!("Key: {}",
//! key.key_id()
//! .map(|keyid| String::from_utf8_lossy(keyid))
//! .unwrap_or_else(|| "missing key ID".into()));
//! if let Ok(key) = key.to_openpgp_key() {
//! eprintln!(" Fingerprint: {}", key.fingerprint());
//! } else {
//! eprintln!(" Not for OpenPGP");
//! }
//! }
//! # Ok(()) }
//! ```
//!
//! You can disable the use of the configuration file by using
//! [`ContextBuilder::disable_config_file`] and then using
//! [`ContextBuilder::add_module`] to specify what modules to load.
//!
//! ## Sign a Message
//!
//! The sample code signs a message using a specified key. We get a
//! key descriptor (a [`Key`]), then use it to instantiate a
//! [`Signer`]. We can do a similar thing to decrypt a message, but
//! in that case we instantiate a [`Decryptor`].
//!
//! ```
//! use sequoia_openpgp as openpgp;
//! use openpgp::crypto::Password;
//! use openpgp::packet::signature::SignatureBuilder;
//! use openpgp::types::SignatureType;
//! # use openpgp::Fingerprint;
//!
//! use sequoia_cryptoki::Context;
//! use sequoia_cryptoki::Prompt;
//! use sequoia_cryptoki::Signer;
//! # use sequoia_cryptoki::ContextBuilder;
//!
//! # fn main() -> sequoia_openpgp::Result<()> {
//! # let fpr: Fingerprint = "EC710462524581C4C3A5224A573784508844731C".parse().expect("valid fingerprint");
//! #
//! # if false {
//! let cryptoki = Context::new()?;
//! # }
//! # let cryptoki = ContextBuilder::new().disable_config_file().build()?;
//!
//! // Get the first key with the specified fingerprint. Note:
//! // there may be multiple keys with the same fingerprint, if the key
//! // was copied.
//! let mut key = None;
//! for k in cryptoki.keys()? {
//! if k.fingerprint().as_ref() == Some(&fpr) {
//! key = Some(k);
//! break;
//! }
//! }
//!
//! let Some(key) = key else {
//! eprintln!("No token has a copy of {}.", fpr);
//! # return Ok(());
//! return Err(anyhow::anyhow!("Key not found"));
//! };
//!
//! // Now, sign a message.
//!
//! // How to prompt the user for a password.
//! struct Prompter;
//! impl Prompt for Prompter {
//! fn prompt_password(&self, _prompt: &str) -> anyhow::Result<Password> {
//! Err(anyhow::anyhow!("Password prompting disabled").into())
//! }
//! }
//!
//! // Turn a `Key` into a `Signer`.
//! let mut signer = Signer::new(Prompter, &key, None, None)?;
//!
//! let msg = b"Hello, world!";
//! let mut sig = SignatureBuilder::new(SignatureType::Binary)
//! .sign_message(&mut signer, msg)?;
//! # Ok(()) }
//! ```
//!
//! ## Find a Key
//!
//! This shows how to use a [`KeySelector`] to select a key by its key
//! ID:
//!
//! ```
//! use sequoia_cryptoki::Context;
//! use sequoia_cryptoki::KeySelector;
//! use sequoia_cryptoki::SelectorScope;
//!
//! # fn main() -> sequoia_openpgp::Result<()> {
//! let cryptoki = Context::new()?;
//! let mut selector = KeySelector::unconstrained();
//! selector.key_id = Some("pgp:v4:eddsa:20251118T090408Z:scrap-heat-mouse".into());
//! match cryptoki.select_one_key(&selector, SelectorScope::PublicKeys) {
//! Ok(key) => {
//! // ...
//! }
//! Err(err) => eprintln!("Key not found"),
//! }
//! # Ok(()) }
//! ```
//!
//! It is also possible to search by unique ID, label and URL. If
//! multiple constraints are specified, then only keys that match all
//! of the constraints are returned.
//!
//! We can do something similar to search for tokens using
//! [`Context::select_one_token`] and [`TokenSelector`].
//!
//! ## Import a Key
//!
//! This example shows how to import a key. We need to first get the
//! token, which we find using [`Context::select_one_token`] (see the
//! previous example). We then open a read-write user session. A
//! session is similar to a transaction: it guarantees that the
//! operations are atomic. A read-write session allows modifying the
//! token, which is what we do when we generate or import a key.
//! Finally, we import the key.
//!
//! ```
//! use anyhow::Context as _;
//! #
//! # use sequoia_openpgp as openpgp;
//! # use openpgp::cert::prelude::*;
//!
//! use sequoia_cryptoki::Context;
//! use sequoia_cryptoki::TokenSelector;
//! use sequoia_cryptoki::KeyCapability;
//!
//! # fn main() -> sequoia_openpgp::Result<()> {
//! # let (cert, _) =
//! # CertBuilder::general_purpose(Some("alice@example.org"))
//! # .generate()?;
//! // Import the primary key.
//! let key = cert.primary_key().key()
//! .parts_as_secret().context("No secret key material")?
//! .role_as_unspecified();
//!
//! let cryptoki = Context::new()?;
//!
//! // Get the token that we want to import the key to.
//! let mut selector = TokenSelector::unconstrained();
//! selector.token_label = Some("some-initialized-token".into());
//! let token = match cryptoki.select_one_token(&selector) {
//! Ok(token) => token,
//! Err(err) => {
//! eprintln!("Token not found");
//! # return Ok(());
//! return Err(err);
//! }
//! };
//!
//! // Open a read/write user session, which is needed to generate or
//! // import a key.
//! let session = token.open_rw_user_session("1234")?;
//!
//! // Import the key.
//! cryptoki.import(&session,
//! token,
//! None, // Import any PQC component to the same token.
//! None, // Use a random label.
//! key,
//! KeyCapability::Signing)?;
//! # Ok(()) }
//! ```
//!
//! ## Generate a Key
//!
//! This code shows how to generate a key on a token. Note: the key
//! cannot normally be exported and thus it is not generally possible
//! to make a backup. As such, it is often better to generate a key
//! in software, save a copy, and import it.
//!
//! The return value is a bare OpenPGP public key packet. You still
//! need to turn it into a certificate by creating a direct signature
//! (using e.g., [`SignatureBuilder::sign_direct_key`]) and adding a
//! user ID, or you need to attach it to an existing certificate with
//! a binding signature (using, e.g., [`CertBuilder::add_subkey`]).
//!
//! [`SignatureBuilder::sign_direct_key`]: https://docs.rs/sequoia-openpgp/latest/sequoia_openpgp/packet/signature/struct.SignatureBuilder.html#method.sign_direct_key
//! [`CertBuilder::add_subkey`]: https://docs.rs/sequoia-openpgp/latest/sequoia_openpgp/cert/struct.CertBuilder.html#method.add_subkey
//!
//! ```
//! use sequoia_openpgp as openpgp;
//! use openpgp::Packet;
//! use openpgp::serialize::Serialize;
//!
//! use sequoia_cryptoki::Context;
//! use sequoia_cryptoki::TokenSelector;
//!
//! # fn main() -> sequoia_openpgp::Result<()> {
//! let cryptoki = Context::new()?;
//!
//! // Get the token that we want to import the key to.
//! let mut selector = TokenSelector::unconstrained();
//! selector.token_label = Some("some-initialized-token".into());
//! let token = match cryptoki.select_one_token(&selector) {
//! Ok(token) => token,
//! Err(err) => {
//! eprintln!("Token not found");
//! # return Ok(());
//! return Err(err);
//! }
//! };
//!
//! // Open a read/write user session, which is needed to generate or
//! // import a key.
//! let session = token.open_rw_user_session("1234")?;
//!
//! // Import the key.
//! let key = cryptoki.generate_eddsa(
//! &session,
//! token,
//! None, // Use the current time.
//! None, // Use a random label.
//! )?;
//! let openpgp_key = Packet::from(key.to_openpgp_key()?.role_into_primary());
//!
//! # let mut output = Vec::new();
//! openpgp_key.serialize(&mut output)?;
//! # Ok(()) }
//! ```
//!
//! # Configuration File
//!
//! By default, [`Context`] and [`ContextBuilder`] read a
//! configuration from the Sequoia home directory. If not using an
//! alternate location, this is
//! `.config/sequoia/keystore/cryptoki/config.toml`. When using an
//! alternate location, this is
//! `$SEQUOIA_HOME/config/keystore/cryptoki/config.toml`.
//!
//! This is a `toml` file, which looks like this:
//!
//! ```toml
//! [[modules]]
//! path = "/usr/local/lib/libkryoptic_pkcs11.so"
//!
//! [[modules]]
//! path = "/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so"
//! ```
//!
//! That is, there is an array of tables named `modules`, and each
//! table contains a single key name `path`, which takes a string and
//! is the path to a cryptoki module to load.
use OnceLock;
use sequoia_openpgp as openpgp;
use Result;
// Re-export any third-party crates that we use in our API.
pub use cryptoki;
pub use PublicKeyAlgorithm;
pub use ContextBuilder;
pub use Config;
pub use ConfigFile;
pub use Error as ConfigError;
pub use Decryptor;
pub use *;
pub use Prompt;
pub use *;
pub use Signer;
pub use KeyCapability;
// This comes near the end so that rustdoc puts all of the generate
// key methods at the end of `Context`'s documentation.
/// Re-export.
pub use toml_edit;
/// Configuration for the PKCS#11 interface.
/// Returns whether the algorithm has a post-quantum component.
/// Returns whether the algorithm has a traditional (non-post
/// quantum) component.
/// Returns whether the algorithm is a composite algorithm, i.e., it
/// has traditional and post quantum components.