Skip to main content

rsa/algorithms/
pad.rs

1//! Conversion between integers and octet strings.
2
3use crate::errors::Result;
4use alloc::vec::Vec;
5use crypto_bigint::{BoxedUint, Choice, CtEq};
6use zeroize::Zeroizing;
7
8/// Writes the big-endian encoding of `bytes` into `out`.
9///
10/// The value must fit in `out`: any bytes truncated from the front must be zero.
11/// In release builds, the amount of data copied depends only on the slice lengths.
12#[inline]
13fn be_pad_into(bytes: &[u8], out: &mut [u8]) {
14    let excess = bytes.len().saturating_sub(out.len());
15    debug_assert!(
16        !bytes[..excess]
17            .iter()
18            .fold(Choice::FALSE, |overflow, byte| overflow | !byte.ct_eq(&0u8))
19            .to_bool(),
20        "integer exceeds output width"
21    );
22
23    out.fill(0);
24    let tail = &bytes[excess..];
25    let start = out.len() - tail.len();
26    out[start..].copy_from_slice(tail);
27}
28
29/// Integer-to-Octet-String Primitive (I2OSP) from [RFC8017 §4.1].
30///
31/// Converts `input` to exactly `padded_len` big-endian bytes, left-padded with zeros.
32/// `input` must fit in `padded_len` bytes. This is a caller-established precondition, checked by a
33/// debug assertion. Unlike the general RFC primitive, this internal helper does not return an
34/// "integer too large" error: callers must establish `input < 256^padded_len` before calling it.
35///
36/// Use [`i2osp_zeroizing`] when encoding secret values.
37///
38/// [RFC8017 §4.1]: https://www.rfc-editor.org/rfc/rfc8017.html#section-4.1
39#[inline]
40pub(crate) fn i2osp(input: BoxedUint, padded_len: usize) -> Vec<u8> {
41    let mut out = vec![0u8; padded_len];
42    be_pad_into(&input.to_be_bytes(), &mut out);
43    out
44}
45
46/// Computes [`i2osp`] (Integer-to-Octet-String Primitive) with zeroization of the input and output
47/// buffers.
48///
49/// The input integer, temporary byte buffer, and returned vector are each zeroized on drop.
50/// The same input-width precondition as [`i2osp`] applies.
51///
52/// For RSA decryption, this computes `EM = I2OSP(m, k)`, where `padded_len` is `k`, the public
53/// modulus length in octets.
54///
55/// [draft-irtf-cfrg-rsa-guidance-10 §7.2] requires this conversion to be constant-time with respect
56/// to `m`. Serialization and copying in this function depend only on `padded_len` and the input's
57/// storage precision. To satisfy that requirement, callers must ensure that both widths are
58/// independent of `m`'s value.
59///
60/// [draft-irtf-cfrg-rsa-guidance-10 §7.2]: https://www.ietf.org/archive/id/draft-irtf-cfrg-rsa-guidance-10.html#section-7.2
61#[inline]
62pub(crate) fn i2osp_zeroizing(input: BoxedUint, padded_len: usize) -> Zeroizing<Vec<u8>> {
63    let input = Zeroizing::new(input);
64    let bytes = Zeroizing::new(input.to_be_bytes());
65    let mut out = Zeroizing::new(vec![0u8; padded_len]);
66    be_pad_into(&bytes, &mut out);
67    out
68}
69
70/// Octet-String-to-Integer Primitive (OS2IP) from [RFC8017 §4.2].
71///
72/// Interprets `input` as a big-endian nonnegative integer with `bits_precision` bits of storage
73/// precision. `bits_precision` must be a multiple of [`Limb::BITS`]. This is a caller-established
74/// precondition, checked by a debug assertion. Returns an error if `input` exceeds that storage
75/// width, even if the excess bytes are zero.
76///
77/// For RSA operations, use the public modulus's storage precision. Ciphertext length and
78/// representative range checks remain the caller's responsibility.
79///
80/// Use [`os2ip_zeroizing`] when decoding secret values.
81///
82/// [RFC8017 §4.2]: https://www.rfc-editor.org/rfc/rfc8017.html#section-4.2
83#[inline]
84#[allow(clippy::integer_division_remainder_used, reason = "debug")]
85pub(crate) fn os2ip(input: &[u8], bits_precision: u32) -> Result<BoxedUint> {
86    debug_assert_eq!(bits_precision % crypto_bigint::Limb::BITS, 0);
87    Ok(BoxedUint::from_be_slice(input, bits_precision)?)
88}
89
90/// Computes [`os2ip`] (Octet-String-to-Integer Primitive) with zeroization of the input and output
91/// buffers.
92///
93/// Takes ownership of the input buffer, which is zeroized on drop, including on error. The
94/// returned integer is also zeroized on drop. The same storage-width precondition and errors as
95/// [`os2ip`] apply.
96///
97/// [draft-irtf-cfrg-rsa-guidance-10 §6.1] requires operations on secret values to be constant-time.
98/// Decoding in this function depends only on `input.len()` and `bits_precision`. To satisfy that
99/// requirement, callers must ensure that both widths are independent of the input's value.
100///
101/// [draft-irtf-cfrg-rsa-guidance-10 §6.1]: https://www.ietf.org/archive/id/draft-irtf-cfrg-rsa-guidance-10.html#section-6.1
102#[inline]
103pub(crate) fn os2ip_zeroizing(
104    input: Zeroizing<Vec<u8>>,
105    bits_precision: u32,
106) -> Result<Zeroizing<BoxedUint>> {
107    os2ip(&input, bits_precision).map(Zeroizing::new)
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    #[test]
114    fn be_pad() {
115        let x = BoxedUint::from(0x0102u64);
116        let p = i2osp(x.clone(), 16);
117        assert_eq!(&p[..14], &[0u8; 14]);
118        assert_eq!(&p[14..], &[1, 2]);
119
120        let p = i2osp_zeroizing(x.clone(), 3);
121        assert_eq!(&p[..], &[0, 1, 2]);
122
123        let p = i2osp(x.clone(), 8);
124        assert_eq!(&p[..], &[0, 0, 0, 0, 0, 0, 1, 2]);
125
126        let p = i2osp(BoxedUint::zero_with_precision(128), 4);
127        assert_eq!(&p[..], &[0u8; 4]);
128    }
129
130    #[cfg(debug_assertions)]
131    #[test]
132    #[should_panic(expected = "integer exceeds output width")]
133    fn be_pad_rejects_broken_precondition() {
134        i2osp_zeroizing(BoxedUint::from(0x0102u64), 1);
135    }
136
137    #[test]
138    fn os2ip_round_trip() {
139        // A 2049-bit modulus uses 257 octets but has a larger, limb-aligned storage precision.
140        let bits_precision = BoxedUint::zero_with_precision(2049).bits_precision();
141        for first_byte in [0, 1, 0xff] {
142            let mut input = vec![0xff; 257];
143            input[0] = first_byte;
144
145            let integer = os2ip(&input, bits_precision).unwrap();
146            assert_eq!(integer.bits_precision(), bits_precision);
147            assert_eq!(i2osp(integer, input.len()), input);
148
149            let integer = os2ip_zeroizing(Zeroizing::new(input.clone()), bits_precision).unwrap();
150            assert_eq!(integer.bits_precision(), bits_precision);
151            let output = i2osp_zeroizing((*integer).clone(), input.len());
152            assert_eq!(*output, input);
153        }
154
155        let zero = os2ip(&[], 128).unwrap();
156        assert_eq!(zero.bits_precision(), 128);
157        assert_eq!(i2osp(zero, 16), [0u8; 16]);
158    }
159
160    #[test]
161    fn os2ip_rejects_oversized_input() {
162        // Leading zeros do not make an encoding fit the requested storage width.
163        let input = vec![0; 17];
164        let expected = crate::errors::Error::Decode(crypto_bigint::DecodeError::InputSize);
165        assert_eq!(os2ip(&input, 128).unwrap_err(), expected);
166        assert_eq!(
167            os2ip_zeroizing(Zeroizing::new(input), 128).unwrap_err(),
168            expected
169        );
170    }
171}