pkcs1/
params.rs

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
//! PKCS#1 RSA parameters.

use crate::{Error, Result};
use der::asn1::{AnyRef, ObjectIdentifier};
use der::{
    asn1::ContextSpecificRef, Decode, DecodeValue, Encode, EncodeValue, FixedTag, Reader, Sequence,
    Tag, TagMode, TagNumber, Writer,
};
use spki::AlgorithmIdentifier;

const OID_SHA_1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.14.3.2.26");
const OID_MGF_1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.8");
const OID_PSPECIFIED: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.9");

// TODO(tarcieri): make `AlgorithmIdentifier` generic around params; use `OID_SHA_1`
const SEQ_OID_SHA_1_DER: &[u8] = &[0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a];

const SHA_1_AI: AlgorithmIdentifier<'_> = AlgorithmIdentifier {
    oid: OID_SHA_1,
    parameters: None,
};

const SALT_LEN_DEFAULT: u8 = 20;

/// `TrailerField` as defined in [RFC 8017 Appendix 2.3].
/// ```text
/// TrailerField ::= INTEGER { trailerFieldBC(1) }
/// ```
/// [RFC 8017 Appendix 2.3]: https://datatracker.ietf.org/doc/html/rfc8017#appendix-A.2.3
#[derive(Clone, Debug, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum TrailerField {
    /// the only supported value (0xbc, default)
    BC = 1,
}

impl Default for TrailerField {
    fn default() -> Self {
        Self::BC
    }
}

impl<'a> DecodeValue<'a> for TrailerField {
    fn decode_value<R: Reader<'a>>(decoder: &mut R, header: der::Header) -> der::Result<Self> {
        match u8::decode_value(decoder, header)? {
            1 => Ok(TrailerField::BC),
            _ => Err(Self::TAG.value_error()),
        }
    }
}

impl EncodeValue for TrailerField {
    fn value_len(&self) -> der::Result<der::Length> {
        Ok(der::Length::ONE)
    }

    fn encode_value(&self, writer: &mut dyn Writer) -> der::Result<()> {
        (*self as u8).encode_value(writer)
    }
}

impl FixedTag for TrailerField {
    const TAG: Tag = Tag::Integer;
}

/// PKCS#1 RSASSA-PSS parameters as defined in [RFC 8017 Appendix 2.3]
///
/// ASN.1 structure containing a serialized RSASSA-PSS parameters:
/// ```text
/// RSASSA-PSS-params ::= SEQUENCE {
///     hashAlgorithm      [0] HashAlgorithm      DEFAULT sha1,
///     maskGenAlgorithm   [1] MaskGenAlgorithm   DEFAULT mgf1SHA1,
///     saltLength         [2] INTEGER            DEFAULT 20,
///     trailerField       [3] TrailerField       DEFAULT trailerFieldBC
/// }
/// HashAlgorithm ::= AlgorithmIdentifier
/// MaskGenAlgorithm ::= AlgorithmIdentifier
/// ```
///
/// [RFC 8017 Appendix 2.3]: https://datatracker.ietf.org/doc/html/rfc8017#appendix-A.2.3
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RsaPssParams<'a> {
    /// Hash Algorithm
    pub hash: AlgorithmIdentifier<'a>,

    /// Mask Generation Function (MGF)
    pub mask_gen: AlgorithmIdentifier<'a>,

    /// Salt length
    pub salt_len: u8,

    /// Trailer field (i.e. [`TrailerField::BC`])
    pub trailer_field: TrailerField,
}

impl<'a> Default for RsaPssParams<'a> {
    fn default() -> Self {
        Self {
            hash: SHA_1_AI,
            mask_gen: default_mgf1_sha1(),
            salt_len: SALT_LEN_DEFAULT,
            trailer_field: Default::default(),
        }
    }
}

impl<'a> DecodeValue<'a> for RsaPssParams<'a> {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: der::Header) -> der::Result<Self> {
        reader.read_nested(header.length, |reader| {
            Ok(Self {
                hash: reader
                    .context_specific(TagNumber::N0, TagMode::Explicit)?
                    .unwrap_or(SHA_1_AI),
                mask_gen: reader
                    .context_specific(TagNumber::N1, TagMode::Explicit)?
                    .unwrap_or_else(default_mgf1_sha1),
                salt_len: reader
                    .context_specific(TagNumber::N2, TagMode::Explicit)?
                    .unwrap_or(SALT_LEN_DEFAULT),
                trailer_field: reader
                    .context_specific(TagNumber::N3, TagMode::Explicit)?
                    .unwrap_or_default(),
            })
        })
    }
}

impl<'a> Sequence<'a> for RsaPssParams<'a> {
    fn fields<F, T>(&self, f: F) -> der::Result<T>
    where
        F: FnOnce(&[&dyn Encode]) -> der::Result<T>,
    {
        f(&[
            &if self.hash == SHA_1_AI {
                None
            } else {
                Some(ContextSpecificRef {
                    tag_number: TagNumber::N0,
                    tag_mode: TagMode::Explicit,
                    value: &self.hash,
                })
            },
            &if self.mask_gen == default_mgf1_sha1() {
                None
            } else {
                Some(ContextSpecificRef {
                    tag_number: TagNumber::N1,
                    tag_mode: TagMode::Explicit,
                    value: &self.mask_gen,
                })
            },
            &if self.salt_len == SALT_LEN_DEFAULT {
                None
            } else {
                Some(ContextSpecificRef {
                    tag_number: TagNumber::N2,
                    tag_mode: TagMode::Explicit,
                    value: &self.salt_len,
                })
            },
            &if self.trailer_field == TrailerField::default() {
                None
            } else {
                Some(ContextSpecificRef {
                    tag_number: TagNumber::N3,
                    tag_mode: TagMode::Explicit,
                    value: &self.trailer_field,
                })
            },
        ])
    }
}

impl<'a> TryFrom<&'a [u8]> for RsaPssParams<'a> {
    type Error = Error;

    fn try_from(bytes: &'a [u8]) -> Result<Self> {
        Ok(Self::from_der(bytes)?)
    }
}

/// Default Mask Generation Function (MGF): SHA-1.
fn default_mgf1_sha1<'a>() -> AlgorithmIdentifier<'a> {
    AlgorithmIdentifier {
        oid: OID_MGF_1,
        parameters: Some(
            AnyRef::new(Tag::Sequence, SEQ_OID_SHA_1_DER)
                .expect("error creating default MGF1 params"),
        ),
    }
}

/// PKCS#1 RSAES-OAEP parameters as defined in [RFC 8017 Appendix 2.1]
///
/// ASN.1 structure containing a serialized RSAES-OAEP parameters:
/// ```text
/// RSAES-OAEP-params ::= SEQUENCE {
///     hashAlgorithm      [0] HashAlgorithm     DEFAULT sha1,
///     maskGenAlgorithm   [1] MaskGenAlgorithm  DEFAULT mgf1SHA1,
///     pSourceAlgorithm   [2] PSourceAlgorithm  DEFAULT pSpecifiedEmpty
/// }
/// HashAlgorithm ::= AlgorithmIdentifier
/// MaskGenAlgorithm ::= AlgorithmIdentifier
/// PSourceAlgorithm ::= AlgorithmIdentifier
/// ```
///
/// [RFC 8017 Appendix 2.1]: https://datatracker.ietf.org/doc/html/rfc8017#appendix-A.2.1
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RsaOaepParams<'a> {
    /// Hash Algorithm
    pub hash: AlgorithmIdentifier<'a>,

    /// Mask Generation Function (MGF)
    pub mask_gen: AlgorithmIdentifier<'a>,

    /// The source (and possibly the value) of the label L
    pub p_source: AlgorithmIdentifier<'a>,
}

impl<'a> Default for RsaOaepParams<'a> {
    fn default() -> Self {
        Self {
            hash: SHA_1_AI,
            mask_gen: default_mgf1_sha1(),
            p_source: default_pempty_string(),
        }
    }
}

impl<'a> DecodeValue<'a> for RsaOaepParams<'a> {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: der::Header) -> der::Result<Self> {
        reader.read_nested(header.length, |reader| {
            Ok(Self {
                hash: reader
                    .context_specific(TagNumber::N0, TagMode::Explicit)?
                    .unwrap_or(SHA_1_AI),
                mask_gen: reader
                    .context_specific(TagNumber::N1, TagMode::Explicit)?
                    .unwrap_or_else(default_mgf1_sha1),
                p_source: reader
                    .context_specific(TagNumber::N2, TagMode::Explicit)?
                    .unwrap_or_else(default_pempty_string),
            })
        })
    }
}

impl<'a> Sequence<'a> for RsaOaepParams<'a> {
    fn fields<F, T>(&self, f: F) -> der::Result<T>
    where
        F: FnOnce(&[&dyn Encode]) -> der::Result<T>,
    {
        f(&[
            &if self.hash == SHA_1_AI {
                None
            } else {
                Some(ContextSpecificRef {
                    tag_number: TagNumber::N0,
                    tag_mode: TagMode::Explicit,
                    value: &self.hash,
                })
            },
            &if self.mask_gen == default_mgf1_sha1() {
                None
            } else {
                Some(ContextSpecificRef {
                    tag_number: TagNumber::N1,
                    tag_mode: TagMode::Explicit,
                    value: &self.mask_gen,
                })
            },
            &if self.p_source == default_pempty_string() {
                None
            } else {
                Some(ContextSpecificRef {
                    tag_number: TagNumber::N2,
                    tag_mode: TagMode::Explicit,
                    value: &self.p_source,
                })
            },
        ])
    }
}

impl<'a> TryFrom<&'a [u8]> for RsaOaepParams<'a> {
    type Error = Error;

    fn try_from(bytes: &'a [u8]) -> Result<Self> {
        Ok(Self::from_der(bytes)?)
    }
}

/// Default Source Algorithm, empty string
fn default_pempty_string<'a>() -> AlgorithmIdentifier<'a> {
    AlgorithmIdentifier {
        oid: OID_PSPECIFIED,
        parameters: Some(
            AnyRef::new(Tag::OctetString, &[]).expect("error creating default OAEP params"),
        ),
    }
}