1// Copyright 2015-2016 Brian Smith.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1415use crate::{bits, digest, error, rand};
1617mod pkcs1;
18mod pss;
1920pub use self::{
21 pkcs1::{RSA_PKCS1_SHA256, RSA_PKCS1_SHA384, RSA_PKCS1_SHA512},
22 pss::{RSA_PSS_SHA256, RSA_PSS_SHA384, RSA_PSS_SHA512},
23};
24pub(super) use pkcs1::RSA_PKCS1_SHA1_FOR_LEGACY_USE_ONLY;
2526/// Common features of both RSA padding encoding and RSA padding verification.
27pub trait Padding: 'static + Sync + crate::sealed::Sealed + core::fmt::Debug {
28// The digest algorithm used for digesting the message (and maybe for
29 // other things).
30fn digest_alg(&self) -> &'static digest::Algorithm;
31}
3233/// An RSA signature encoding as described in [RFC 3447 Section 8].
34///
35/// [RFC 3447 Section 8]: https://tools.ietf.org/html/rfc3447#section-8
36#[cfg(feature = "alloc")]
37pub trait RsaEncoding: Padding {
38#[doc(hidden)]
39fn encode(
40&self,
41 m_hash: digest::Digest,
42 m_out: &mut [u8],
43 mod_bits: bits::BitLength,
44 rng: &dyn rand::SecureRandom,
45 ) -> Result<(), error::Unspecified>;
46}
4748/// Verification of an RSA signature encoding as described in
49/// [RFC 3447 Section 8].
50///
51/// [RFC 3447 Section 8]: https://tools.ietf.org/html/rfc3447#section-8
52pub trait Verification: Padding {
53fn verify(
54&self,
55 m_hash: digest::Digest,
56 m: &mut untrusted::Reader,
57 mod_bits: bits::BitLength,
58 ) -> Result<(), error::Unspecified>;
59}
6061// Masks `out` with the output of the mask-generating function MGF1 as
62// described in https://tools.ietf.org/html/rfc3447#appendix-B.2.1.
63fn mgf1(digest_alg: &'static digest::Algorithm, seed: &[u8], out: &mut [u8]) {
64let digest_len = digest_alg.output_len();
6566// Maximum counter value is the value of (mask_len / digest_len) rounded up.
67for (i, out) in out.chunks_mut(digest_len).enumerate() {
68let mut ctx = digest::Context::new(digest_alg);
69 ctx.update(seed);
70// The counter will always fit in a `u32` because we reject absurdly
71 // long inputs very early.
72ctx.update(&u32::to_be_bytes(i.try_into().unwrap()));
73let digest = ctx.finish();
74// `zip` does the right thing as the the last chunk may legitimately be
75 // shorter than `digest`, and `digest` will never be shorter than `out`.
76for (m, &d) in out.iter_mut().zip(digest.as_ref().iter()) {
77*m ^= d;
78 }
79 }
80}
8182#[cfg(test)]
83mod test {
84use super::*;
85use crate::{digest, error, test};
86use alloc::vec;
8788#[test]
89fn test_pss_padding_verify() {
90 test::run(
91test_file!("rsa_pss_padding_tests.txt"),
92 |section, test_case| {
93assert_eq!(section, "");
9495let digest_name = test_case.consume_string("Digest");
96let alg = match digest_name.as_ref() {
97"SHA256" => &RSA_PSS_SHA256,
98"SHA384" => &RSA_PSS_SHA384,
99"SHA512" => &RSA_PSS_SHA512,
100_ => panic!("Unsupported digest: {}", digest_name),
101 };
102103let msg = test_case.consume_bytes("Msg");
104let msg = untrusted::Input::from(&msg);
105let m_hash = digest::digest(alg.digest_alg(), msg.as_slice_less_safe());
106107let encoded = test_case.consume_bytes("EM");
108let encoded = untrusted::Input::from(&encoded);
109110// Salt is recomputed in verification algorithm.
111let _ = test_case.consume_bytes("Salt");
112113let bit_len = test_case.consume_usize_bits("Len");
114let is_valid = test_case.consume_string("Result") == "P";
115116let actual_result =
117 encoded.read_all(error::Unspecified, |m| alg.verify(m_hash, m, bit_len));
118assert_eq!(actual_result.is_ok(), is_valid);
119120Ok(())
121 },
122 );
123 }
124125// Tests PSS encoding for various public modulus lengths.
126#[cfg(feature = "alloc")]
127 #[test]
128fn test_pss_padding_encode() {
129 test::run(
130test_file!("rsa_pss_padding_tests.txt"),
131 |section, test_case| {
132assert_eq!(section, "");
133134let digest_name = test_case.consume_string("Digest");
135let alg = match digest_name.as_ref() {
136"SHA256" => &RSA_PSS_SHA256,
137"SHA384" => &RSA_PSS_SHA384,
138"SHA512" => &RSA_PSS_SHA512,
139_ => panic!("Unsupported digest: {}", digest_name),
140 };
141142let msg = test_case.consume_bytes("Msg");
143let salt = test_case.consume_bytes("Salt");
144let encoded = test_case.consume_bytes("EM");
145let bit_len = test_case.consume_usize_bits("Len");
146let expected_result = test_case.consume_string("Result");
147148// Only test the valid outputs
149if expected_result != "P" {
150return Ok(());
151 }
152153let rng = test::rand::FixedSliceRandom { bytes: &salt };
154155let mut m_out = vec![0u8; bit_len.as_usize_bytes_rounded_up()];
156let digest = digest::digest(alg.digest_alg(), &msg);
157 alg.encode(digest, &mut m_out, bit_len, &rng).unwrap();
158assert_eq!(m_out, encoded);
159160Ok(())
161 },
162 );
163 }
164}