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
/// RSASSA-PKCS1-v1_5 using SHA-256.
use openssl::{
    bn::BigNum,
    hash::MessageDigest,
    pkey::{Id, PKey, Private, Public},
    rsa::{Padding, Rsa},
    sign::{RsaPssSaltlen, Signer, Verifier},
};
use smallvec::SmallVec;

use crate::{
    jwk::Jwk, url_safe_trailing_bits, Error, PrivateKeyToJwk, PublicKeyToJwk, Result, SigningKey,
    VerificationKey,
};

/// RSA signature algorithms.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RsaAlgorithm {
    RS256,
    RS384,
    RS512,
    PS256,
    PS384,
    PS512,
}

impl RsaAlgorithm {
    pub fn is_pss(self) -> bool {
        matches!(
            self,
            RsaAlgorithm::PS256 | RsaAlgorithm::PS384 | RsaAlgorithm::PS512
        )
    }

    fn digest(self) -> MessageDigest {
        use RsaAlgorithm::*;
        match self {
            RS256 | PS256 => MessageDigest::sha256(),
            RS384 | PS384 => MessageDigest::sha384(),
            RS512 | PS512 => MessageDigest::sha512(),
        }
    }

    pub fn name(self) -> &'static str {
        use RsaAlgorithm::*;
        match self {
            RS256 => "RS256",
            RS384 => "RS384",
            RS512 => "RS512",
            PS256 => "PS256",
            PS384 => "PS384",
            PS512 => "PS512",
        }
    }

    pub fn from_name(name: &str) -> Result<Self> {
        Ok(match name {
            "RS256" => RsaAlgorithm::RS256,
            "RS384" => RsaAlgorithm::RS384,
            "RS512" => RsaAlgorithm::RS512,
            "PS256" => RsaAlgorithm::PS256,
            "PS384" => RsaAlgorithm::PS384,
            "PS512" => RsaAlgorithm::PS512,
            _ => return Err(Error::UnsupportedOrInvalidKey),
        })
    }
}

/// RSA Private Key.
///
/// By default, it only verifies signatures generated by the same algorithm used
/// for signing. If you want to verify signatures generated by any RSA
/// algorithm, set `verify_any` to `true`.
#[derive(Debug, Clone)]
pub struct RsaPrivateKey {
    private_key: PKey<Private>,
    pub algorithm: RsaAlgorithm,
    pub verify_any: bool,
}

impl RsaPrivateKey {
    /// bits >= 2048.
    pub fn generate(bits: u32, algorithm: RsaAlgorithm) -> Result<Self> {
        if bits < 2048 {
            return Err(Error::UnsupportedOrInvalidKey);
        }

        Ok(Self {
            private_key: PKey::from_rsa(Rsa::generate(bits)?)?,
            algorithm,
            verify_any: false,
        })
    }

    pub(crate) fn from_pkey(pkey: PKey<Private>, algorithm: RsaAlgorithm) -> Result<Self> {
        if pkey.bits() < 2048 || !pkey.rsa()?.check_key()? {
            return Err(Error::UnsupportedOrInvalidKey);
        }
        Ok(Self {
            private_key: pkey,
            algorithm,
            verify_any: false,
        })
    }

    pub(crate) fn from_pkey_without_check(
        pkey: PKey<Private>,
        algorithm: RsaAlgorithm,
    ) -> Result<Self> {
        if pkey.bits() < 2048 {
            return Err(Error::UnsupportedOrInvalidKey);
        }
        Ok(Self {
            private_key: pkey,
            algorithm,
            verify_any: false,
        })
    }

    pub fn from_pem(pem: &[u8], algorithm: RsaAlgorithm) -> Result<Self> {
        let pk = PKey::private_key_from_pem(pem)?;
        Self::from_pkey(pk, algorithm)
    }

    pub fn private_key_to_pem_pkcs8(&self) -> Result<String> {
        Ok(String::from_utf8(
            self.private_key.private_key_to_pem_pkcs8()?,
        )?)
    }

    pub fn public_key_to_pem(&self) -> Result<String> {
        Ok(String::from_utf8(self.private_key.public_key_to_pem()?)?)
    }

    pub fn public_key_to_pem_pkcs1(&self) -> Result<String> {
        Ok(String::from_utf8(
            self.private_key.rsa()?.public_key_to_pem_pkcs1()?,
        )?)
    }

    pub fn n(&self) -> Result<Vec<u8>> {
        Ok(self.private_key.rsa()?.n().to_vec())
    }

    pub fn e(&self) -> Result<Vec<u8>> {
        Ok(self.private_key.rsa()?.e().to_vec())
    }
}

impl PrivateKeyToJwk for RsaPrivateKey {
    #[allow(clippy::many_single_char_names)]
    fn private_key_to_jwk(&self) -> Result<Jwk> {
        let n = self.n()?;
        let e = self.e()?;
        let rsa = self.private_key.rsa()?;
        let d = rsa.d().to_vec();
        let p = rsa.p().map(|p| p.to_vec());
        let q = rsa.q().map(|q| q.to_vec());
        let dp = rsa.dmp1().map(|dp| dp.to_vec());
        let dq = rsa.dmq1().map(|dq| dq.to_vec());
        let qi = rsa.iqmp().map(|qi| qi.to_vec());
        fn encode(x: &[u8]) -> String {
            base64::encode_config(x, url_safe_trailing_bits())
        }
        Ok(Jwk {
            kty: "RSA".into(),
            alg: if self.verify_any {
                None
            } else {
                Some(self.algorithm.name().into())
            },
            use_: Some("sig".into()),
            n: Some(encode(&n)),
            e: Some(encode(&e)),
            d: Some(encode(&d)),
            p: p.map(|p| encode(&p)),
            q: q.map(|q| encode(&q)),
            dp: dp.map(|dp| encode(&dp)),
            dq: dq.map(|dq| encode(&dq)),
            qi: qi.map(|qi| encode(&qi)),
            ..Default::default()
        })
    }
}

impl PublicKeyToJwk for RsaPrivateKey {
    fn public_key_to_jwk(&self) -> Result<Jwk> {
        Ok(Jwk {
            kty: "RSA".into(),
            alg: if self.verify_any {
                None
            } else {
                Some(self.algorithm.name().into())
            },
            use_: Some("sig".into()),
            n: Some(base64::encode_config(self.n()?, url_safe_trailing_bits())),
            e: Some(base64::encode_config(self.e()?, url_safe_trailing_bits())),
            ..Jwk::default()
        })
    }
}

/// RSA Public Key.
#[derive(Debug)]
pub struct RsaPublicKey {
    public_key: PKey<Public>,
    /// If this is `None`, this key verifies signatures generated by ANY RSA
    /// algorithms. Otherwise it ONLY verifies signatures generated by this
    /// algorithm.
    pub algorithm: Option<RsaAlgorithm>,
}

impl RsaPublicKey {
    pub(crate) fn from_pkey(pkey: PKey<Public>, algorithm: Option<RsaAlgorithm>) -> Result<Self> {
        if pkey.id() != Id::RSA || pkey.bits() < 2048 {
            return Err(Error::UnsupportedOrInvalidKey);
        }
        Ok(Self {
            public_key: pkey,
            algorithm,
        })
    }

    /// Both `BEGIN PUBLIC KEY` and `BEGIN RSA PUBLIC KEY` are OK.
    pub fn from_pem(pem: &[u8], algorithm: Option<RsaAlgorithm>) -> Result<Self> {
        if std::str::from_utf8(pem).map_or(false, |pem| pem.contains("BEGIN RSA")) {
            let rsa = Rsa::public_key_from_pem_pkcs1(pem)?;
            Self::from_pkey(PKey::from_rsa(rsa)?, algorithm)
        } else {
            let pkey = PKey::public_key_from_pem(pem)?;
            Self::from_pkey(pkey, algorithm)
        }
    }

    pub fn from_components(n: &[u8], e: &[u8], algorithm: Option<RsaAlgorithm>) -> Result<Self> {
        let rsa = Rsa::from_public_components(BigNum::from_slice(n)?, BigNum::from_slice(e)?)?;
        Self::from_pkey(PKey::from_rsa(rsa)?, algorithm)
    }

    /// BEGIN PUBLIC KEY
    pub fn to_pem(&self) -> Result<String> {
        Ok(String::from_utf8(self.public_key.public_key_to_pem()?)?)
    }

    /// BEGIN RSA PUBLIC KEY
    pub fn to_pem_pkcs1(&self) -> Result<String> {
        Ok(String::from_utf8(
            self.public_key.rsa()?.public_key_to_pem_pkcs1()?,
        )?)
    }

    pub fn n(&self) -> Result<Vec<u8>> {
        Ok(self.public_key.rsa()?.n().to_vec())
    }

    pub fn e(&self) -> Result<Vec<u8>> {
        Ok(self.public_key.rsa()?.e().to_vec())
    }
}

impl PublicKeyToJwk for RsaPublicKey {
    fn public_key_to_jwk(&self) -> Result<Jwk> {
        Ok(Jwk {
            kty: "RSA".into(),
            alg: self.algorithm.map(|alg| alg.name().to_string()),
            use_: Some("sig".into()),
            n: Some(base64::encode_config(self.n()?, url_safe_trailing_bits())),
            e: Some(base64::encode_config(self.e()?, url_safe_trailing_bits())),
            ..Jwk::default()
        })
    }
}

impl SigningKey for RsaPrivateKey {
    fn sign(&self, v: &[u8]) -> Result<SmallVec<[u8; 64]>> {
        let mut signer = Signer::new(self.algorithm.digest(), self.private_key.as_ref())?;
        if self.algorithm.is_pss() {
            signer.set_rsa_padding(Padding::PKCS1_PSS)?;
            signer.set_rsa_pss_saltlen(RsaPssSaltlen::DIGEST_LENGTH)?;
        }

        signer.update(v)?;
        Ok(signer.sign_to_vec()?.into())
    }

    fn alg(&self) -> &'static str {
        self.algorithm.name()
    }
}

impl VerificationKey for RsaPrivateKey {
    fn verify(&self, v: &[u8], sig: &[u8], alg: &str) -> Result<()> {
        let alg = if self.verify_any {
            RsaAlgorithm::from_name(alg)?
        } else {
            if alg != self.algorithm.name() {
                return Err(Error::VerificationError);
            }
            self.algorithm
        };

        let mut verifier = Verifier::new(alg.digest(), self.private_key.as_ref())?;
        if alg.is_pss() {
            verifier.set_rsa_padding(Padding::PKCS1_PSS)?;
            verifier.set_rsa_pss_saltlen(RsaPssSaltlen::DIGEST_LENGTH)?;
        }
        if verifier.verify_oneshot(sig, v)? {
            Ok(())
        } else {
            Err(Error::VerificationError)
        }
    }
}

impl VerificationKey for RsaPublicKey {
    fn verify(&self, v: &[u8], sig: &[u8], alg: &str) -> Result<()> {
        let alg = if let Some(self_alg) = self.algorithm {
            if self_alg.name() != alg {
                return Err(Error::VerificationError);
            }
            self_alg
        } else {
            RsaAlgorithm::from_name(alg)?
        };

        let mut verifier = Verifier::new(alg.digest(), self.public_key.as_ref())?;
        if alg.is_pss() {
            verifier.set_rsa_padding(Padding::PKCS1_PSS)?;
            verifier.set_rsa_pss_saltlen(RsaPssSaltlen::DIGEST_LENGTH)?;
        }
        if verifier.verify_oneshot(sig, v)? {
            Ok(())
        } else {
            Err(Error::VerificationError)
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        ecdsa::{EcdsaAlgorithm, EcdsaPrivateKey},
        SomePrivateKey,
    };

    use super::*;

    #[test]
    fn conversion() -> Result<()> {
        let k = RsaPrivateKey::generate(2048, RsaAlgorithm::PS384)?;
        let pem = k.private_key_to_pem_pkcs8()?;
        RsaPrivateKey::from_pem(pem.as_bytes(), RsaAlgorithm::PS384)?;

        let es256key_pem =
            EcdsaPrivateKey::generate(EcdsaAlgorithm::ES256)?.private_key_to_pem_pkcs8()?;
        assert!(RsaPrivateKey::from_pem(es256key_pem.as_bytes(), RsaAlgorithm::PS384).is_err());

        let pk_pem = k.public_key_to_pem()?;
        let pk_pem_pkcs1 = k.public_key_to_pem_pkcs1()?;

        let pk = RsaPublicKey::from_pem(pk_pem.as_bytes(), None)?;
        let pk1 = RsaPublicKey::from_pem(pk_pem_pkcs1.as_bytes(), None)?;

        println!("pk: {:?}", pk);

        let pk_pem1 = pk1.to_pem()?;
        let pk_pem_pkcs1_1 = pk.to_pem_pkcs1()?;

        assert_eq!(pk_pem, pk_pem1);
        assert_eq!(pk_pem_pkcs1, pk_pem_pkcs1_1);

        assert_eq!(k.alg(), "PS384");

        if let SomePrivateKey::Rsa(k1) = k
            .private_key_to_jwk()?
            .to_signing_key(RsaAlgorithm::RS512)?
        {
            assert!(k.private_key.public_eq(k1.private_key.as_ref()));
        } else {
            panic!("expected rsa private key");
        }

        k.public_key_to_jwk()?.to_verification_key()?;
        pk.public_key_to_jwk()?;

        Ok(())
    }

    #[test]
    fn test_private_key_from_jwk_n_e_d_only() -> Result<()> {
        let k = RsaPrivateKey::generate(2048, RsaAlgorithm::PS256)?;
        let mut jwk = k.private_key_to_jwk()?;
        jwk.p = None;
        jwk.q = None;
        jwk.dp = None;
        jwk.dq = None;
        jwk.qi = None;
        let k1 = jwk.to_signing_key(RsaAlgorithm::RS256)?;
        let sig = k1.sign(b"msg")?;
        k.verify(b"msg", &sig, "PS256")?;
        k1.verify(b"msg", &sig, "PS256")?;
        let sig = k.sign(b"msg")?;
        k1.verify(b"msg", &sig, "PS256")?;
        Ok(())
    }

    #[test]
    fn sign_verify() -> Result<()> {
        for alg in [
            RsaAlgorithm::RS256,
            RsaAlgorithm::RS384,
            RsaAlgorithm::RS512,
            RsaAlgorithm::PS256,
            RsaAlgorithm::PS384,
            RsaAlgorithm::PS512,
        ] {
            let k = RsaPrivateKey::generate(2048, alg)?;
            let pk = RsaPublicKey::from_pem(k.public_key_to_pem()?.as_bytes(), None)?;
            let sig = k.sign(b"...")?;
            assert!(k.verify(b"...", &sig, alg.name()).is_ok());
            assert!(k.verify(b"...", &sig, "WRONG ALG").is_err());
            assert!(k.verify(b"....", &sig, alg.name()).is_err());
            assert!(pk.verify(b"...", &sig, alg.name()).is_ok());
            assert!(pk.verify(b"....", &sig, alg.name()).is_err());
        }
        Ok(())
    }
}