purecrypto 0.6.29

A pure-Rust cryptography toolkit with no foreign-code dependencies, from constant-time primitives up to keys, X.509 and TLS.
Documentation
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Per-call parameters for signing, verification, and RSA/SM2 encryption.
//!
//! A single call selects the hash, padding, context, and signature encoding an
//! operation uses. The [`Default`] is always valid, and each builder method
//! records that its field was *explicitly set*.
//!
//! # Loud rejection of unsupported parameters
//!
//! These structs are **consume-tracked**: an algorithm reads the fields it
//! honours through a [`SignParamsReader`] (or [`CryptParamsReader`]) and then
//! calls [`finish`](SignParamsReader::finish). `finish` fails with
//! [`Error::UnsupportedParam`](crate::key::Error::UnsupportedParam) if the
//! caller explicitly set a field the algorithm did **not** read — so setting an
//! RSA padding on an Ed25519 key, or a digest on a scheme that fixes its own,
//! is rejected rather than silently ignored. An algorithm therefore never has
//! to check for parameters it doesn't use: it just reads what it needs and the
//! reader reports the rest. (The RNG is a separate argument, not a parameter, so
//! passing one to a deterministic scheme is never an error.)

use crate::key::Error;

/// A hash function, selected at runtime — the crate-wide
/// [`HashAlgorithm`](crate::hash::HashAlgorithm) enum, re-exported here under
/// the name these parameters use.
///
/// Used by RSA and ECDSA (which are parameterised by a digest) and as the
/// OAEP/MGF1 hash for RSA encryption. EdDSA and the post-quantum schemes fix
/// their own internal hash and ignore this.
///
/// The enum names every digest the crate implements, but a *signature* scheme
/// accepts only the subset it has a standardised encoding for: through this
/// facade RSA and ECDSA take SHA-1 and SHA-224/256/384/512, and anything else
/// fails with [`Error::UnsupportedParam`](crate::key::Error::UnsupportedParam)
/// naming `hash`. The generic per-algorithm APIs (e.g.
/// [`sign_pss::<D>`](crate::rsa::RsaPrivateKey::sign_pss)) remain open to any
/// [`Digest`](crate::hash::Digest).
pub use crate::hash::HashAlgorithm as Hash;

/// Runs `$body` with `$d` aliased to the concrete digest type named by a
/// runtime [`Hash`] — the bridge from the parameter enum into the generic
/// `sign_pss::<D>` / `verify::<D>` / `encrypt_oaep::<D>` APIs.
///
/// The accepted set is the *policy* of this facade, stated once here rather
/// than per algorithm: SHA-1 and SHA-224/256/384/512, i.e. exactly the digests
/// with a standardised PKCS#1 `DigestInfo` and X.509/TLS signature encoding
/// (every one of them also implements [`Pkcs1Digest`](crate::rsa::Pkcs1Digest),
/// so the PSS, OAEP and PKCS#1 v1.5 paths all share this macro). Any other
/// digest is refused with [`Error::UnsupportedParam`] rather than silently
/// falling back to one the caller did not ask for; callers wanting e.g. PSS
/// over SHA-3 use the generic per-algorithm API directly.
///
/// The expansion `return`s on the unsupported arm, so every use must sit in a
/// function returning `Result<_, crate::key::Error>`.
macro_rules! dispatch_key_hash {
    ($h:expr, |$d:ident| $body:block) => {
        match $h {
            $crate::key::Hash::Sha256 => {
                type $d = $crate::hash::Sha256;
                $body
            }
            $crate::key::Hash::Sha384 => {
                type $d = $crate::hash::Sha384;
                $body
            }
            $crate::key::Hash::Sha512 => {
                type $d = $crate::hash::Sha512;
                $body
            }
            $crate::key::Hash::Sha224 => {
                type $d = $crate::hash::Sha224;
                $body
            }
            $crate::key::Hash::Sha1 => {
                type $d = $crate::hash::Sha1;
                $body
            }
            _ => {
                return Err($crate::key::Error::UnsupportedParam { param: "hash" });
            }
        }
    };
}

pub(crate) use dispatch_key_hash;

/// RSA signature padding scheme.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RsaSigPadding {
    /// RSASSA-PSS (PKCS#1 v2.1) with the given salt length.
    Pss {
        /// The PSS salt length.
        salt_len: SaltLen,
    },
    /// RSASSA-PKCS1-v1_5 (PKCS#1 v1.5).
    Pkcs1v15,
}

/// PSS salt length.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SaltLen {
    /// Salt length equal to the digest output length (the common default).
    DigestLength,
    /// The maximum salt length the modulus allows.
    Max,
    /// A fixed salt length in bytes.
    Fixed(usize),
}

/// RSA encryption padding scheme.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RsaEncPadding {
    /// RSAES-OAEP (PKCS#1 v2.1) with the given digest and MGF1 hash.
    Oaep {
        /// The OAEP label/digest hash.
        hash: Hash,
        /// The MGF1 hash (commonly the same as `hash`).
        mgf1: Hash,
    },
    /// RSAES-PKCS1-v1_5 (PKCS#1 v1.5).
    Pkcs1v15,
}

/// Wire encoding for ECDSA / SM2 signatures (see [`SignParams::sig_encoding`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum SigEncoding {
    /// Fixed-width `r || s` (each coordinate big-endian, padded to the field
    /// width). Used by JWS/COSE and the low-level fixed-curve APIs.
    #[default]
    Raw,
    /// ASN.1 DER `Ecdsa-Sig-Value ::= SEQUENCE { r INTEGER, s INTEGER }` — the
    /// X.509, TLS, and OpenSSL encoding.
    Der,
}

// Field bits for the consume-tracking masks.
const F_HASH: u8 = 1 << 0;
const F_PREHASHED: u8 = 1 << 1;
const F_CONTEXT: u8 = 1 << 2;
const F_PADDING: u8 = 1 << 3;
const F_DETERMINISTIC: u8 = 1 << 4;
const F_SIG_ENCODING: u8 = 1 << 5;

const F_ENC_PADDING: u8 = 1 << 0;
const F_ENC_LABEL: u8 = 1 << 1;

/// Parameters for a signing or verification call.
///
/// Built with [`SignParams::new`] (or [`Default`]) plus chained setters. Which
/// fields each algorithm honours:
///
/// * `hash`, `prehashed` — RSA and ECDSA.
/// * `padding` — RSA.
/// * `sig_encoding` — ECDSA and SM2.
/// * `context` — Ed448, ML-DSA, SLH-DSA, and the SM2 signer ID.
/// * `deterministic` — ML-DSA / SLH-DSA.
///
/// Setting a field an algorithm does not honour makes the call fail with
/// [`Error::UnsupportedParam`](crate::key::Error::UnsupportedParam); see the
/// [module docs](crate::key).
#[derive(Debug, Clone, Copy)]
pub struct SignParams<'a> {
    hash: Hash,
    prehashed: bool,
    context: &'a [u8],
    padding: RsaSigPadding,
    deterministic: bool,
    sig_encoding: SigEncoding,
    set: u8,
}

impl Default for SignParams<'_> {
    fn default() -> Self {
        SignParams {
            hash: Hash::Sha256,
            prehashed: false,
            context: &[],
            padding: RsaSigPadding::Pss {
                salt_len: SaltLen::DigestLength,
            },
            deterministic: false,
            sig_encoding: SigEncoding::Raw,
            set: 0,
        }
    }
}

impl<'a> SignParams<'a> {
    /// Default parameters: nothing explicitly set, so every algorithm accepts
    /// them (RSA defaults to PSS/SHA-256, ECDSA/SM2 to raw `r||s`, etc.).
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the digest (RSA / ECDSA).
    pub fn hash(mut self, hash: Hash) -> Self {
        self.hash = hash;
        self.set |= F_HASH;
        self
    }

    /// Marks the message as a prehash, already digested (RSA / ECDSA).
    pub fn prehashed(mut self, yes: bool) -> Self {
        self.prehashed = yes;
        self.set |= F_PREHASHED;
        self
    }

    /// Sets the context string (Ed448 / ML-DSA / SLH-DSA) or SM2 signer ID.
    pub fn context(mut self, context: &'a [u8]) -> Self {
        self.context = context;
        self.set |= F_CONTEXT;
        self
    }

    /// Sets the signature wire encoding (ECDSA / SM2).
    pub fn sig_encoding(mut self, enc: SigEncoding) -> Self {
        self.sig_encoding = enc;
        self.set |= F_SIG_ENCODING;
        self
    }

    /// Uses RSASSA-PKCS1-v1_5 padding instead of the default PSS (RSA).
    pub fn pkcs1v15(mut self) -> Self {
        self.padding = RsaSigPadding::Pkcs1v15;
        self.set |= F_PADDING;
        self
    }

    /// Uses RSASSA-PSS padding with the given salt length (RSA).
    pub fn pss(mut self, salt_len: SaltLen) -> Self {
        self.padding = RsaSigPadding::Pss { salt_len };
        self.set |= F_PADDING;
        self
    }

    /// Selects the deterministic variant (ML-DSA / SLH-DSA).
    pub fn deterministic(mut self, yes: bool) -> Self {
        self.deterministic = yes;
        self.set |= F_DETERMINISTIC;
        self
    }

    /// Begins consuming the parameters. An algorithm implementation reads the
    /// fields it honours through the returned reader, then calls
    /// [`finish`](SignParamsReader::finish).
    pub fn reader(&self) -> SignParamsReader<'a> {
        SignParamsReader {
            params: *self,
            used: 0,
        }
    }
}

/// Consume-tracking reader over [`SignParams`] (see the [module docs](crate::key)).
///
/// Each accessor returns the field's value (the caller's, or the default) and
/// records that the field was honoured. [`finish`](Self::finish) then rejects
/// any field the caller explicitly set but the algorithm did not read.
#[derive(Debug)]
pub struct SignParamsReader<'a> {
    params: SignParams<'a>,
    used: u8,
}

impl<'a> SignParamsReader<'a> {
    /// The digest to use.
    pub fn hash(&mut self) -> Hash {
        self.used |= F_HASH;
        self.params.hash
    }

    /// Whether the message is a prehash.
    pub fn prehashed(&mut self) -> bool {
        self.used |= F_PREHASHED;
        self.params.prehashed
    }

    /// The context string / SM2 signer ID.
    pub fn context(&mut self) -> &'a [u8] {
        self.used |= F_CONTEXT;
        self.params.context
    }

    /// The RSA padding scheme.
    pub fn padding(&mut self) -> RsaSigPadding {
        self.used |= F_PADDING;
        self.params.padding
    }

    /// Whether to use the deterministic variant.
    pub fn deterministic(&mut self) -> bool {
        self.used |= F_DETERMINISTIC;
        self.params.deterministic
    }

    /// The signature wire encoding.
    pub fn sig_encoding(&mut self) -> SigEncoding {
        self.used |= F_SIG_ENCODING;
        self.params.sig_encoding
    }

    /// Rejects any field the caller set but the algorithm did not read.
    pub fn finish(self) -> Result<(), Error> {
        match first_unconsumed(self.params.set & !self.used, SIGN_PARAM_NAMES) {
            Some(param) => Err(Error::UnsupportedParam { param }),
            None => Ok(()),
        }
    }
}

const SIGN_PARAM_NAMES: &[(u8, &str)] = &[
    (F_HASH, "hash"),
    (F_PREHASHED, "prehashed"),
    (F_CONTEXT, "context"),
    (F_PADDING, "padding"),
    (F_DETERMINISTIC, "deterministic"),
    (F_SIG_ENCODING, "sig_encoding"),
];

const CRYPT_PARAM_NAMES: &[(u8, &str)] = &[(F_ENC_PADDING, "padding"), (F_ENC_LABEL, "label")];

fn first_unconsumed(leftover: u8, names: &[(u8, &'static str)]) -> Option<&'static str> {
    if leftover == 0 {
        return None;
    }
    for &(bit, name) in names {
        if leftover & bit != 0 {
            return Some(name);
        }
    }
    Some("parameter")
}

/// Parameters for an encryption or decryption call (RSA / SM2).
///
/// `padding` and `label` apply to **RSA** only; SM2 public-key encryption fixes
/// its own scheme and honours neither — setting them on an SM2 key fails with
/// [`Error::UnsupportedParam`](crate::key::Error::UnsupportedParam). For
/// decryption the padding and label must match what the sender used.
#[derive(Debug, Clone, Copy)]
pub struct CryptParams<'a> {
    padding: RsaEncPadding,
    label: &'a [u8],
    set: u8,
}

/// Parameters for an encryption call. See [`CryptParams`].
pub type EncryptParams<'a> = CryptParams<'a>;
/// Parameters for a decryption call. See [`CryptParams`].
pub type DecryptParams<'a> = CryptParams<'a>;

impl Default for CryptParams<'_> {
    fn default() -> Self {
        CryptParams {
            padding: RsaEncPadding::Oaep {
                hash: Hash::Sha256,
                mgf1: Hash::Sha256,
            },
            label: &[],
            set: 0,
        }
    }
}

impl<'a> CryptParams<'a> {
    /// Default parameters: nothing explicitly set (RSA defaults to OAEP/SHA-256,
    /// no label).
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the RSA padding scheme.
    pub fn padding(mut self, padding: RsaEncPadding) -> Self {
        self.padding = padding;
        self.set |= F_ENC_PADDING;
        self
    }

    /// Sets the OAEP label (RSA-OAEP).
    pub fn label(mut self, label: &'a [u8]) -> Self {
        self.label = label;
        self.set |= F_ENC_LABEL;
        self
    }

    /// Begins consuming the parameters (see [`SignParams::reader`]).
    pub fn reader(&self) -> CryptParamsReader<'a> {
        CryptParamsReader {
            params: *self,
            used: 0,
        }
    }
}

/// Consume-tracking reader over [`CryptParams`] (see the [module docs](crate::key)).
#[derive(Debug)]
pub struct CryptParamsReader<'a> {
    params: CryptParams<'a>,
    used: u8,
}

impl<'a> CryptParamsReader<'a> {
    /// The RSA padding scheme.
    pub fn padding(&mut self) -> RsaEncPadding {
        self.used |= F_ENC_PADDING;
        self.params.padding
    }

    /// The OAEP label.
    pub fn label(&mut self) -> &'a [u8] {
        self.used |= F_ENC_LABEL;
        self.params.label
    }

    /// Rejects any field the caller set but the algorithm did not read.
    pub fn finish(self) -> Result<(), Error> {
        match first_unconsumed(self.params.set & !self.used, CRYPT_PARAM_NAMES) {
            Some(param) => Err(Error::UnsupportedParam { param }),
            None => Ok(()),
        }
    }
}