ring/rsa/
public_modulus.rs
1use crate::{
2 arithmetic::{bigint, montgomery::RR},
3 bits::{self, FromUsizeBytes as _},
4 cpu, error,
5 rsa::N,
6};
7use core::ops::RangeInclusive;
8
9#[derive(Clone)]
11pub struct PublicModulus {
12 value: bigint::OwnedModulus<N>,
13 oneRR: bigint::One<N, RR>,
14}
15
16impl PublicModulus {
24 pub(super) fn from_be_bytes(
25 n: untrusted::Input,
26 allowed_bit_lengths: RangeInclusive<bits::BitLength>,
27 cpu_features: cpu::Features,
28 ) -> Result<Self, error::KeyRejected> {
29 let min_bits = *allowed_bit_lengths.start();
33 let max_bits = *allowed_bit_lengths.end();
34
35 const MIN_BITS: bits::BitLength = bits::BitLength::from_usize_bits(1024);
39
40 let value = bigint::OwnedModulus::from_be_bytes(n)?;
42 let bits = value.len_bits();
43
44 assert!(min_bits >= MIN_BITS);
48 let bits_rounded_up =
49 bits::BitLength::from_usize_bytes(bits.as_usize_bytes_rounded_up()).unwrap(); if bits_rounded_up < min_bits {
51 return Err(error::KeyRejected::too_small());
52 }
53 if bits > max_bits {
54 return Err(error::KeyRejected::too_large());
55 }
56 let oneRR = bigint::One::newRR(&value.modulus(cpu_features));
57
58 Ok(Self { value, oneRR })
59 }
60
61 pub fn be_bytes(&self) -> impl ExactSizeIterator<Item = u8> + Clone + '_ {
65 self.value.be_bytes()
66 }
67
68 pub fn len_bits(&self) -> bits::BitLength {
70 self.value.len_bits()
71 }
72
73 pub(super) fn value(&self, cpu_features: cpu::Features) -> bigint::Modulus<N> {
74 self.value.modulus(cpu_features)
75 }
76
77 pub(super) fn oneRR(&self) -> &bigint::Elem<N, RR> {
78 self.oneRR.as_ref()
79 }
80}