jose 0.0.2

A JSON Object Signing and Encryption implementation
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! The primitives for working with [RSA] encryption.
//!
//! [RSA]: https://en.wikipedia.org/wiki/RSA_cryptosystem

use alloc::{boxed::Box, format, string::String, vec::Vec};
use core::{convert::Infallible, fmt};

use serde::{de::Error as _, ser::Error as _, Deserialize, Serialize};

use super::backend::{
    interface::{
        self,
        rsa::{self, PrivateKey as _, PublicKey as _},
    },
    Backend,
};
use crate::{
    base64_url::{Base64UrlBytes, SecretBase64UrlBytes},
    crypto::Result,
    jwa::{self, RsaSigning},
    jwk::{self, FromKey, IntoJsonWebKey},
    jws::{self, InvalidSigningAlgorithmError},
    Base64UrlString,
};

type BackendPublicKey = <Backend as interface::Backend>::RsaPublicKey;
type BackendPrivateKey = <Backend as interface::Backend>::RsaPrivateKey;

/// The returned signature from a sign operation.
#[repr(transparent)]
pub struct Signature {
    inner: <BackendPrivateKey as rsa::PrivateKey>::Signature,
}

impl From<Signature> for Vec<u8> {
    fn from(value: Signature) -> Self {
        value.as_ref().to_vec()
    }
}

impl AsRef<[u8]> for Signature {
    fn as_ref(&self) -> &[u8] {
        self.inner.as_ref()
    }
}

impl fmt::Debug for Signature {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.as_ref(), f)
    }
}

/// The RSA public key type.
#[derive(Clone)]
pub struct PublicKey {
    inner: BackendPublicKey,
}

impl Eq for PublicKey {}
impl PartialEq for PublicKey {
    fn eq(&self, o: &Self) -> bool {
        let this_pub = rsa::PublicKey::components(&self.inner);
        let o_pub = rsa::PublicKey::components(&o.inner);

        this_pub == o_pub
    }
}

impl fmt::Debug for PublicKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let key = rsa::PublicKey::components(&self.inner);
        let n = Base64UrlString::encode(key.n);
        let e = Base64UrlString::encode(key.e);

        f.debug_struct("PublicKey")
            .field("n", &n)
            .field("e", &e)
            .finish()
    }
}

impl From<PublicKey> for jwk::JsonWebKeyType {
    fn from(x: PublicKey) -> Self {
        jwk::JsonWebKeyType::Asymmetric(Box::new(jwk::AsymmetricJsonWebKey::Public(
            jwk::Public::Rsa(x),
        )))
    }
}

impl crate::sealed::Sealed for PublicKey {}
impl IntoJsonWebKey for PublicKey {
    type Algorithm = RsaSigning;
    type Error = Infallible;

    fn into_jwk(
        self,
        alg: Option<impl Into<Self::Algorithm>>,
    ) -> Result<crate::JsonWebKey, Self::Error> {
        let alg = alg.map(|rsa| {
            jwa::JsonWebAlgorithm::Signing(jwa::JsonWebSigningAlgorithm::Rsa(rsa.into()))
        });

        let key = jwk::JsonWebKeyType::Asymmetric(Box::new(jwk::AsymmetricJsonWebKey::Public(
            jwk::Public::Rsa(self),
        )));

        Ok(jwk::JsonWebKey::new_with_algorithm(key, alg))
    }
}

impl jwk::Thumbprint for PublicKey {
    fn thumbprint_prehashed(&self) -> String {
        crate::jwk::thumbprint::serialize_key_thumbprint(self)
    }
}

impl Serialize for PublicKey {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        #[derive(Serialize)]
        struct Repr {
            kty: &'static str,

            n: Base64UrlBytes,
            e: Base64UrlBytes,
        }

        let key = rsa::PublicKey::components(&self.inner);
        Repr {
            kty: "RSA",
            n: Base64UrlBytes(key.n),
            e: Base64UrlBytes(key.e),
        }
        .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for PublicKey {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Repr {
            kty: String,

            n: Base64UrlBytes,
            e: Base64UrlBytes,
        }

        let repr = Repr::deserialize(deserializer)?;

        if &*repr.kty != "RSA" {
            return Err(D::Error::custom("`kty` field is required to be `RSA`"));
        }

        let components = rsa::PublicKeyComponents {
            n: repr.n.0,
            e: repr.e.0,
        };
        let key = rsa::PublicKey::from_components(components)
            .map_err(|e| D::Error::custom(format!("failed to construct RSA public key: {}", e)))?;
        Ok(Self { inner: key })
    }
}

/// The RSA private key type.
#[derive(Clone)]
pub struct PrivateKey {
    inner: BackendPrivateKey,
}

impl PrivateKey {
    /// Generate a new RSA key pair of the given bit size.
    ///
    /// # Errors
    ///
    /// Returns an [`Err`] if the key generation fails.
    pub fn generate(bits: usize) -> Result<Self> {
        let key = BackendPrivateKey::generate(bits)?;
        Ok(Self { inner: key })
    }

    /// Get the public key corresponding to this private key.
    pub fn to_public_key(&self) -> PublicKey {
        PublicKey {
            inner: self.inner.to_public_key(),
        }
    }
}

impl Eq for PrivateKey {}
impl PartialEq for PrivateKey {
    fn eq(&self, o: &Self) -> bool {
        self.to_public_key() == o.to_public_key()
    }
}

impl From<PrivateKey> for jwk::JsonWebKeyType {
    fn from(x: PrivateKey) -> Self {
        jwk::JsonWebKeyType::Asymmetric(Box::new(jwk::AsymmetricJsonWebKey::Private(
            jwk::Private::Rsa(Box::new(x)),
        )))
    }
}

impl fmt::Debug for PrivateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let key = rsa::PrivateKey::public_components(&self.inner);
        let n = Base64UrlString::encode(key.n);
        let e = Base64UrlString::encode(key.e);

        f.debug_struct("PrivateKey")
            .field("n", &n)
            .field("e", &e)
            .field("primes", &"[REDACTED]")
            .finish()
    }
}

impl crate::sealed::Sealed for PrivateKey {}
impl IntoJsonWebKey for PrivateKey {
    type Algorithm = RsaSigning;
    type Error = Infallible;

    fn into_jwk(
        self,
        alg: Option<impl Into<Self::Algorithm>>,
    ) -> Result<crate::JsonWebKey, Self::Error> {
        let alg = alg.map(|rsa| {
            jwa::JsonWebAlgorithm::Signing(jwa::JsonWebSigningAlgorithm::Rsa(rsa.into()))
        });

        let key = jwk::JsonWebKeyType::Asymmetric(Box::new(jwk::AsymmetricJsonWebKey::Private(
            jwk::Private::Rsa(Box::new(self)),
        )));

        Ok(crate::JsonWebKey::new_with_algorithm(key, alg))
    }
}

impl jwk::Thumbprint for PrivateKey {
    fn thumbprint_prehashed(&self) -> String {
        self.to_public_key().thumbprint_prehashed()
    }
}

impl Serialize for PrivateKey {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        #[derive(Serialize)]
        struct Repr {
            kty: &'static str,

            n: Base64UrlBytes,
            e: Base64UrlBytes,

            d: SecretBase64UrlBytes,
            p: SecretBase64UrlBytes,
            q: SecretBase64UrlBytes,
            dp: SecretBase64UrlBytes,
            dq: SecretBase64UrlBytes,
            qi: SecretBase64UrlBytes,
        }

        let pub_key = rsa::PrivateKey::public_components(&self.inner);
        let key = rsa::PrivateKey::private_components(&self.inner).map_err(S::Error::custom)?;

        let repr = Repr {
            kty: "RSA",
            n: Base64UrlBytes(pub_key.n),
            e: Base64UrlBytes(pub_key.e),
            d: SecretBase64UrlBytes(key.d),
            p: SecretBase64UrlBytes(key.prime.p),
            q: SecretBase64UrlBytes(key.prime.q),
            dp: SecretBase64UrlBytes(key.prime.dp),
            dq: SecretBase64UrlBytes(key.prime.dq),
            qi: SecretBase64UrlBytes(key.prime.qi),
        };

        repr.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for PrivateKey {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Repr {
            kty: String,

            n: Base64UrlBytes,
            e: Base64UrlBytes,
            d: SecretBase64UrlBytes,

            p: Option<SecretBase64UrlBytes>,
            q: Option<SecretBase64UrlBytes>,
            dp: Option<SecretBase64UrlBytes>,
            dq: Option<SecretBase64UrlBytes>,
            qi: Option<SecretBase64UrlBytes>,

            oth: Option<serde_json::Value>,
        }

        let repr = Repr::deserialize(deserializer)?;

        if &*repr.kty != "RSA" {
            return Err(D::Error::custom("`kty` field is required to be `RSA`"));
        }

        // RFC:
        //
        // The parameter "d" is REQUIRED for RSA private keys.  The others enable
        // optimizations and SHOULD be included by producers of JWKs
        // representing RSA private keys.  If the producer includes any of the
        // other private key parameters, then all of the others MUST be present,
        // with the exception of "oth", which MUST only be present when more than two
        // prime factors were used.

        let any_prime_present = repr.p.is_some()
            | repr.q.is_some()
            | repr.dp.is_some()
            | repr.dq.is_some()
            | repr.qi.is_some();

        let prime_info = if any_prime_present {
            let err = |field: &str| {
                D::Error::custom(format!(
                    "expected `{}` to be present because all prime fields must be set if one of \
                     them is set",
                    field
                ))
            };

            rsa::PrivateKeyPrimeComponents {
                p: repr.p.ok_or_else(|| err("p"))?.0,
                q: repr.q.ok_or_else(|| err("q"))?.0,
                dp: repr.dp.ok_or_else(|| err("dp"))?.0,
                dq: repr.dq.ok_or_else(|| err("dq"))?.0,
                qi: repr.qi.ok_or_else(|| err("qi"))?.0,
            }
        } else {
            // FIXME: can we support RSA keys without any primes?
            return Err(D::Error::custom(
                "RSA private keys without any primes are not supported",
            ));
        };

        if repr.oth.is_some() {
            // FIXME: Support additional primes
            return Err(D::Error::custom(
                "RSA private keys with `oth` field set are not supported",
            ));
        }

        let pub_components = rsa::PublicKeyComponents {
            n: repr.n.0,
            e: repr.e.0,
        };

        let priv_components = rsa::PrivateKeyComponents {
            d: repr.d.0,
            prime: prime_info,
        };

        let key = rsa::PrivateKey::from_components(priv_components, pub_components)
            .map_err(|e| D::Error::custom(format!("failed to construct RSA private key: {e}")))?;
        Ok(Self { inner: key })
    }
}

/// A [`Signer`](jws::Signer) using an [`PrivateKey`] and an RSA algorithm.
#[derive(Debug)]
pub struct Signer {
    key: PrivateKey,
    alg: RsaSigning,
}

impl FromKey<PrivateKey> for Signer {
    type Error = InvalidSigningAlgorithmError;

    fn from_key(value: PrivateKey, alg: jwa::JsonWebAlgorithm) -> Result<Self, Self::Error> {
        match alg {
            jwa::JsonWebAlgorithm::Signing(jwa::JsonWebSigningAlgorithm::Rsa(alg)) => {
                Ok(Self { key: value, alg })
            }
            _ => Err(InvalidSigningAlgorithmError),
        }
    }
}

impl jws::Signer<Signature> for Signer {
    fn sign(&mut self, msg: &[u8]) -> Result<Signature> {
        let sig = self.key.inner.sign(self.alg, msg)?;
        Ok(Signature { inner: sig })
    }

    fn algorithm(&self) -> jwa::JsonWebSigningAlgorithm {
        jwa::JsonWebSigningAlgorithm::Rsa(self.alg)
    }
}

/// A [`Verifier`](jws::Verifier) using an [`PublicKey`] and an RSA algorithm.
#[derive(Debug)]
pub struct Verifier {
    key: PublicKey,
    alg: RsaSigning,
}

impl FromKey<PublicKey> for Verifier {
    type Error = InvalidSigningAlgorithmError;

    fn from_key(value: PublicKey, alg: jwa::JsonWebAlgorithm) -> Result<Self, Self::Error> {
        match alg {
            jwa::JsonWebAlgorithm::Signing(jwa::JsonWebSigningAlgorithm::Rsa(alg)) => {
                Ok(Self { key: value, alg })
            }
            _ => Err(InvalidSigningAlgorithmError),
        }
    }
}

impl FromKey<PrivateKey> for Verifier {
    type Error = InvalidSigningAlgorithmError;

    /// Create a [`Verifier`] from the private key by
    /// turning it into the public key and dropping the private parts afterwards
    fn from_key(value: PrivateKey, alg: jwa::JsonWebAlgorithm) -> Result<Self, Self::Error> {
        Self::from_key(value.to_public_key(), alg)
    }
}

impl jws::Verifier for Verifier {
    fn verify(&mut self, msg: &[u8], signature: &[u8]) -> Result<(), jws::VerifyError> {
        match self.key.inner.verify(self.alg, msg, signature) {
            Ok(true) => Ok(()),
            Ok(false) => Err(jws::VerifyError::InvalidSignature),
            Err(err) => Err(jws::VerifyError::CryptoBackend(err)),
        }
    }
}