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
use rand::thread_rng;
use rand_core::{CryptoRng, RngCore};
use rsa::{hash::Hash, BigUint, PaddingScheme, PublicKey, RSAPrivateKey, RSAPublicKey};
use sha2::{Digest, Sha256, Sha384, Sha512};
use thiserror::Error;

use std::borrow::Cow;

use crate::{Algorithm, AlgorithmSignature};

/// Errors that may occur during token parsing.
#[derive(Debug, Error)]
pub enum RsaError {
    #[error("Unsupported signature length")]
    UnsupportedSignatureLength,
    #[error("Unsupported modulus size")]
    UnsupportedModulusSize,
    #[error("Invalid key: {0}")]
    InvalidKey(rsa::errors::Error),
    #[error("Key generation error: {0}")]
    KeygenError(rsa::errors::Error),
}

#[derive(Debug)]
pub struct Signature(Vec<u8>);

impl AlgorithmSignature for Signature {
    fn try_from_slice(bytes: &[u8]) -> anyhow::Result<Self> {
        match bytes.len() {
            256 | 384 | 512 => Ok(Signature(bytes.to_vec())),
            _ => Err(RsaError::UnsupportedSignatureLength.into()),
        }
    }

    fn as_bytes(&self) -> Cow<[u8]> {
        Cow::Owned(self.0.clone())
    }
}

/// RSA padding algorithm.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Padding {
    /// PKCS1v1.5
    Pkcs1v15,
    /// PSS
    Pss,
}

/// An RSA public key.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct RsaVerifyingKey(RSAPublicKey);

impl AsRef<RSAPublicKey> for RsaVerifyingKey {
    fn as_ref(&self) -> &RSAPublicKey {
        &self.0
    }
}

impl RsaVerifyingKey {
    /// Create a verification key from a DER-encoded set of the parameters.
    pub fn from_der(der: &[u8]) -> anyhow::Result<RsaVerifyingKey> {
        match RSAPublicKey::from_pkcs8(&der) {
            Err(e) => Err(RsaError::InvalidKey(e).into()),
            Ok(key) => Ok(RsaVerifyingKey(key)),
        }
    }

    /// Create a verification key from a modulus and a public exponent.
    pub fn from_components(n: &[u8], e: &[u8]) -> anyhow::Result<RsaVerifyingKey> {
        let n = BigUint::from_bytes_be(n);
        let e = BigUint::from_bytes_be(e);
        match RSAPublicKey::new(n, e) {
            Err(e) => Err(RsaError::InvalidKey(e).into()),
            Ok(key) => Ok(RsaVerifyingKey(key)),
        }
    }
}

/// An RSA signing key.
#[derive(Debug)]
pub struct RsaSigningKey(RSAPrivateKey);

impl AsRef<RSAPrivateKey> for RsaSigningKey {
    fn as_ref(&self) -> &RSAPrivateKey {
        &self.0
    }
}

impl RsaSigningKey {
    /// Create a signing key from a DER-encoded set of the parameters.
    pub fn from_der(der: &[u8]) -> anyhow::Result<RsaSigningKey> {
        match RSAPrivateKey::from_pkcs8(&der) {
            Err(e) => Err(RsaError::InvalidKey(e).into()),
            Ok(key) => {
                key.validate().map_err(RsaError::InvalidKey)?;
                Ok(RsaSigningKey(key))
            }
        }
    }

    /// Convert a signing key to a verification key.
    pub fn to_verifying_key(&self) -> RsaVerifyingKey {
        RsaVerifyingKey(RSAPublicKey::from(&self.0))
    }
}

/// Integrity algorithm using digital signatures on RSA-PKCS1v1.5 and SHA-256.
///
/// The name of the algorithm is specified as `RS256` as per the [IANA registry].
///
/// *This type is available if the crate is built with the `rsa` feature.*
///
/// [IANA registry]: https://www.iana.org/assignments/jose/jose.xhtml
#[derive(Debug)]
pub struct Rsa {
    hash_alg: Hash,
    padding_alg: Padding,
}

impl Rsa {
    /// Create an instance using a specific hash function and padding
    pub fn new(hash_alg: Hash, padding_alg: Padding) -> Self {
        Rsa {
            hash_alg,
            padding_alg,
        }
    }
}

pub trait RsaVariant {
    fn rsa() -> Rsa;
}

impl<T: RsaVariant> Algorithm for T {
    type SigningKey = RsaSigningKey;
    type VerifyingKey = RsaVerifyingKey;
    type Signature = Signature;

    fn name(&self) -> Cow<'static, str> {
        Self::rsa().name()
    }

    fn sign(&self, signing_key: &Self::SigningKey, message: &[u8]) -> Self::Signature {
        Self::rsa().sign(signing_key, message)
    }

    fn verify_signature(
        &self,
        signature: &Self::Signature,
        verifying_key: &Self::VerifyingKey,
        message: &[u8],
    ) -> bool {
        Self::rsa().verify_signature(signature, verifying_key, message)
    }
}

impl Rsa {
    fn hash(&self, message: &[u8]) -> Vec<u8> {
        match self.hash_alg {
            Hash::SHA2_256 => Sha256::digest(message).to_vec(),
            Hash::SHA2_384 => Sha384::digest(message).to_vec(),
            Hash::SHA2_512 => Sha512::digest(message).to_vec(),
            _ => unreachable!(),
        }
    }

    fn padding_scheme(&self) -> PaddingScheme {
        match self.padding_alg {
            Padding::Pkcs1v15 => PaddingScheme::new_pkcs1v15_sign(Some(self.hash_alg)),
            Padding::Pss => {
                let rng = rand_core::OsRng {};
                match self.hash_alg {
                    Hash::SHA2_256 => PaddingScheme::new_pss::<Sha256, _>(rng),
                    Hash::SHA2_384 => PaddingScheme::new_pss::<Sha384, _>(rng),
                    Hash::SHA2_512 => PaddingScheme::new_pss::<Sha512, _>(rng),
                    _ => unreachable!(),
                }
            }
        }
    }

    fn name(&self) -> Cow<'static, str> {
        let name = match self.hash_alg {
            Hash::SHA2_256 => "RS256",
            Hash::SHA2_384 => "RS384",
            Hash::SHA2_512 => "RS512",
            _ => unreachable!(),
        };
        Cow::Borrowed(name)
    }

    fn sign(&self, signing_key: &RsaSigningKey, message: &[u8]) -> Signature {
        let digest = self.hash(message);
        let mut rng = thread_rng();
        Signature(
            signing_key
                .as_ref()
                .sign_blinded(&mut rng, self.padding_scheme(), &digest)
                .expect("Unexpected RSA signature failure"),
        )
    }

    fn verify_signature(
        &self,
        signature: &Signature,
        verifying_key: &RsaVerifyingKey,
        message: &[u8],
    ) -> bool {
        let digest = self.hash(message);
        verifying_key
            .as_ref()
            .verify(self.padding_scheme(), &digest, &signature.0)
            .is_ok()
    }

    /// Generate a new key pair.
    pub fn generate<R: CryptoRng + RngCore>(
        rng: &mut R,
        modulus_bits: usize,
    ) -> anyhow::Result<(RsaSigningKey, RsaVerifyingKey)> {
        match modulus_bits {
            2048 | 3072 | 4096 => {}
            _ => return Err(RsaError::UnsupportedModulusSize.into()),
        }
        let signing_key = match RSAPrivateKey::new(rng, modulus_bits) {
            Err(e) => return Err(RsaError::KeygenError(e).into()),
            Ok(key) => RsaSigningKey(key),
        };
        let verifying_key = signing_key.to_verifying_key();
        Ok((signing_key, verifying_key))
    }
}

/// RSA-PKCS1v1.5 with SHA-256 as a hash function
#[derive(Debug)]
pub struct Rs256;

impl RsaVariant for Rs256 {
    fn rsa() -> Rsa {
        Rsa::new(Hash::SHA2_256, Padding::Pkcs1v15)
    }
}

/// RSA-PKCS1v1.5 with SHA-384 as a hash function
#[derive(Debug)]
pub struct Rs384;

impl RsaVariant for Rs384 {
    fn rsa() -> Rsa {
        Rsa::new(Hash::SHA2_384, Padding::Pkcs1v15)
    }
}

/// RSA-PKCS1v1.5 with SHA-512 as a hash function
#[derive(Debug)]
pub struct Rs512;

impl RsaVariant for Rs512 {
    fn rsa() -> Rsa {
        Rsa::new(Hash::SHA2_512, Padding::Pkcs1v15)
    }
}

/// RSASSA-PSS with SHA-256 as a hash function
#[derive(Debug)]
pub struct Ps256;

impl RsaVariant for Ps256 {
    fn rsa() -> Rsa {
        Rsa::new(Hash::SHA2_256, Padding::Pss)
    }
}

/// RSASSA-PSS with SHA-384 as a hash function
#[derive(Debug)]
pub struct Ps384;

impl RsaVariant for Ps384 {
    fn rsa() -> Rsa {
        Rsa::new(Hash::SHA2_384, Padding::Pss)
    }
}

/// RSASSA-PSS with SHA-512 as a hash function
#[derive(Debug)]
pub struct Ps512;

impl RsaVariant for Ps512 {
    fn rsa() -> Rsa {
        Rsa::new(Hash::SHA2_512, Padding::Pss)
    }
}