rsa/algorithms/
pad.rs

1//! Special handling for converting the BigUint to u8 vectors
2
3use alloc::vec::Vec;
4use num_bigint::BigUint;
5use zeroize::Zeroizing;
6
7use crate::errors::{Error, Result};
8
9/// Returns a new vector of the given length, with 0s left padded.
10#[inline]
11fn left_pad(input: &[u8], padded_len: usize) -> Result<Vec<u8>> {
12    if input.len() > padded_len {
13        return Err(Error::InvalidPadLen);
14    }
15
16    let mut out = vec![0u8; padded_len];
17    out[padded_len - input.len()..].copy_from_slice(input);
18    Ok(out)
19}
20
21/// Converts input to the new vector of the given length, using BE and with 0s left padded.
22#[inline]
23pub(crate) fn uint_to_be_pad(input: BigUint, padded_len: usize) -> Result<Vec<u8>> {
24    left_pad(&input.to_bytes_be(), padded_len)
25}
26
27/// Converts input to the new vector of the given length, using BE and with 0s left padded.
28#[inline]
29pub(crate) fn uint_to_zeroizing_be_pad(input: BigUint, padded_len: usize) -> Result<Vec<u8>> {
30    let m = Zeroizing::new(input);
31    let m = Zeroizing::new(m.to_bytes_be());
32    left_pad(&m, padded_len)
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38    #[test]
39    fn test_left_pad() {
40        const INPUT_LEN: usize = 3;
41        let input = vec![0u8; INPUT_LEN];
42
43        // input len < padded len
44        let padded = left_pad(&input, INPUT_LEN + 1).unwrap();
45        assert_eq!(padded.len(), INPUT_LEN + 1);
46
47        // input len == padded len
48        let padded = left_pad(&input, INPUT_LEN).unwrap();
49        assert_eq!(padded.len(), INPUT_LEN);
50
51        // input len > padded len
52        let padded = left_pad(&input, INPUT_LEN - 1);
53        assert!(padded.is_err());
54    }
55}