1use self::boxed_limbs::BoxedLimbs;
40pub(crate) use self::{
41 modulus::{Modulus, OwnedModulus},
42 modulusvalue::OwnedModulusValue,
43 private_exponent::PrivateExponent,
44};
45use super::{inout::AliasingSlices3, limbs512, montgomery::*, LimbSliceError, MAX_LIMBS};
46use crate::{
47 bits::BitLength,
48 c,
49 error::{self, LenMismatchError},
50 limb::{self, Limb, LIMB_BITS},
51 polyfill::slice::{self, AsChunks},
52};
53use core::{
54 marker::PhantomData,
55 num::{NonZeroU64, NonZeroUsize},
56};
57
58mod boxed_limbs;
59mod modulus;
60mod modulusvalue;
61mod private_exponent;
62
63pub trait PublicModulus {}
64
65pub struct Storage<M> {
69 limbs: BoxedLimbs<M>,
70}
71
72impl<M, E> From<Elem<M, E>> for Storage<M> {
73 fn from(elem: Elem<M, E>) -> Self {
74 Self { limbs: elem.limbs }
75 }
76}
77
78pub struct Elem<M, E = Unencoded> {
84 limbs: BoxedLimbs<M>,
85
86 encoding: PhantomData<E>,
89}
90
91impl<M, E> Elem<M, E> {
92 pub fn clone_into(&self, mut out: Storage<M>) -> Self {
93 out.limbs.copy_from_slice(&self.limbs);
94 Self {
95 limbs: out.limbs,
96 encoding: self.encoding,
97 }
98 }
99}
100
101impl<M, E> Elem<M, E> {
102 #[inline]
103 pub fn is_zero(&self) -> bool {
104 limb::limbs_are_zero(&self.limbs).leak()
105 }
106}
107
108fn from_montgomery_amm<M>(mut in_out: Storage<M>, m: &Modulus<M>) -> Elem<M, Unencoded> {
114 let mut one = [0; MAX_LIMBS];
115 one[0] = 1;
116 let one = &one[..m.limbs().len()];
117 limbs_mul_mont(
118 (&mut in_out.limbs[..], one),
119 m.limbs(),
120 m.n0(),
121 m.cpu_features(),
122 )
123 .unwrap_or_else(unwrap_impossible_limb_slice_error);
124 Elem {
125 limbs: in_out.limbs,
126 encoding: PhantomData,
127 }
128}
129
130#[cfg(any(test, not(target_arch = "x86_64")))]
131impl<M> Elem<M, R> {
132 #[inline]
133 pub fn into_unencoded(self, m: &Modulus<M>) -> Elem<M, Unencoded> {
134 from_montgomery_amm(Storage::from(self), m)
135 }
136}
137
138impl<M> Elem<M, Unencoded> {
139 pub fn from_be_bytes_padded(
140 input: untrusted::Input,
141 m: &Modulus<M>,
142 ) -> Result<Self, error::Unspecified> {
143 Ok(Self {
144 limbs: BoxedLimbs::from_be_bytes_padded_less_than(input, m)?,
145 encoding: PhantomData,
146 })
147 }
148
149 #[inline]
150 pub fn fill_be_bytes(&self, out: &mut [u8]) {
151 limb::big_endian_from_limbs(&self.limbs, out)
153 }
154}
155
156pub fn elem_mul_into<M, AF, BF>(
157 mut out: Storage<M>,
158 a: &Elem<M, AF>,
159 b: &Elem<M, BF>,
160 m: &Modulus<M>,
161) -> Elem<M, <(AF, BF) as ProductEncoding>::Output>
162where
163 (AF, BF): ProductEncoding,
164{
165 limbs_mul_mont(
166 (out.limbs.as_mut(), b.limbs.as_ref(), a.limbs.as_ref()),
167 m.limbs(),
168 m.n0(),
169 m.cpu_features(),
170 )
171 .unwrap_or_else(unwrap_impossible_limb_slice_error);
172 Elem {
173 limbs: out.limbs,
174 encoding: PhantomData,
175 }
176}
177
178pub fn elem_mul<M, AF, BF>(
179 a: &Elem<M, AF>,
180 mut b: Elem<M, BF>,
181 m: &Modulus<M>,
182) -> Elem<M, <(AF, BF) as ProductEncoding>::Output>
183where
184 (AF, BF): ProductEncoding,
185{
186 limbs_mul_mont(
187 (&mut b.limbs[..], &a.limbs[..]),
188 m.limbs(),
189 m.n0(),
190 m.cpu_features(),
191 )
192 .unwrap_or_else(unwrap_impossible_limb_slice_error);
193 Elem {
194 limbs: b.limbs,
195 encoding: PhantomData,
196 }
197}
198
199fn elem_double<M, AF>(r: &mut Elem<M, AF>, m: &Modulus<M>) {
201 limb::limbs_double_mod(&mut r.limbs, m.limbs())
202 .unwrap_or_else(unwrap_impossible_len_mismatch_error)
203}
204
205pub fn elem_reduced_once<A, M>(
210 mut r: Storage<M>,
211 a: &Elem<A, Unencoded>,
212 m: &Modulus<M>,
213 other_modulus_len_bits: BitLength,
214) -> Elem<M, Unencoded> {
215 assert_eq!(m.len_bits(), other_modulus_len_bits);
216 r.limbs.copy_from_slice(&a.limbs);
217 limb::limbs_reduce_once(&mut r.limbs, m.limbs())
218 .unwrap_or_else(unwrap_impossible_len_mismatch_error);
219 Elem {
220 limbs: r.limbs,
221 encoding: PhantomData,
222 }
223}
224
225#[inline]
226pub fn elem_reduced<Larger, Smaller>(
227 mut r: Storage<Smaller>,
228 a: &Elem<Larger, Unencoded>,
229 m: &Modulus<Smaller>,
230 other_prime_len_bits: BitLength,
231) -> Elem<Smaller, RInverse> {
232 assert_eq!(other_prime_len_bits, m.len_bits());
236
237 assert_eq!(a.limbs.len(), m.limbs().len() * 2);
239
240 let mut tmp = [0; MAX_LIMBS];
241 let tmp = &mut tmp[..a.limbs.len()];
242 tmp.copy_from_slice(&a.limbs);
243
244 limbs_from_mont_in_place(&mut r.limbs, tmp, m.limbs(), m.n0());
245 Elem {
246 limbs: r.limbs,
247 encoding: PhantomData,
248 }
249}
250
251#[inline]
252fn elem_squared<M, E>(
253 mut a: Elem<M, E>,
254 m: &Modulus<M>,
255) -> Elem<M, <(E, E) as ProductEncoding>::Output>
256where
257 (E, E): ProductEncoding,
258{
259 limbs_square_mont(&mut a.limbs, m.limbs(), m.n0(), m.cpu_features())
260 .unwrap_or_else(unwrap_impossible_limb_slice_error);
261 Elem {
262 limbs: a.limbs,
263 encoding: PhantomData,
264 }
265}
266
267pub fn elem_widen<Larger, Smaller>(
268 mut r: Storage<Larger>,
269 a: Elem<Smaller, Unencoded>,
270 m: &Modulus<Larger>,
271 smaller_modulus_bits: BitLength,
272) -> Result<Elem<Larger, Unencoded>, error::Unspecified> {
273 if smaller_modulus_bits >= m.len_bits() {
274 return Err(error::Unspecified);
275 }
276 let (to_copy, to_zero) = r.limbs.split_at_mut(a.limbs.len());
277 to_copy.copy_from_slice(&a.limbs);
278 to_zero.fill(0);
279 Ok(Elem {
280 limbs: r.limbs,
281 encoding: PhantomData,
282 })
283}
284
285pub fn elem_add<M, E>(mut a: Elem<M, E>, b: Elem<M, E>, m: &Modulus<M>) -> Elem<M, E> {
287 limb::limbs_add_assign_mod(&mut a.limbs, &b.limbs, m.limbs())
288 .unwrap_or_else(unwrap_impossible_len_mismatch_error);
289 a
290}
291
292pub fn elem_sub<M, E>(mut a: Elem<M, E>, b: &Elem<M, E>, m: &Modulus<M>) -> Elem<M, E> {
294 prefixed_extern! {
295 fn LIMBS_sub_mod(
297 r: *mut Limb,
298 a: *const Limb,
299 b: *const Limb,
300 m: *const Limb,
301 num_limbs: c::NonZero_size_t,
302 );
303 }
304 let num_limbs = NonZeroUsize::new(m.limbs().len()).unwrap();
305 (a.limbs.as_mut(), b.limbs.as_ref())
306 .with_non_dangling_non_null_pointers_rab(num_limbs, |r, a, b| {
307 let m = m.limbs().as_ptr(); unsafe { LIMBS_sub_mod(r, a, b, m, num_limbs) }
309 })
310 .unwrap_or_else(unwrap_impossible_len_mismatch_error);
311 a
312}
313
314pub struct One<M, E>(Elem<M, E>);
316
317impl<M> One<M, RR> {
318 pub(crate) fn newRR(mut out: Storage<M>, m: &Modulus<M>) -> Self {
326 let w = m.limbs().len();
328
329 let r = w * LIMB_BITS;
331
332 m.oneR(&mut out.limbs);
333 let mut acc: Elem<M, R> = Elem {
334 limbs: out.limbs,
335 encoding: PhantomData,
336 };
337
338 let t = w;
349 let z = w.trailing_zeros();
350 let d = w >> z;
351 debug_assert_eq!(w, d * (1 << z));
352 debug_assert!(d <= t);
353 debug_assert!(t < r);
354 for _ in 0..t {
355 elem_double(&mut acc, m);
356 }
357
358 const B: u32 = if cfg!(target_pointer_width = "64") {
380 6
381 } else if cfg!(target_pointer_width = "32") {
382 5
383 } else {
384 panic!("unsupported target_pointer_width")
385 };
386 #[allow(clippy::assertions_on_constants)]
387 const _LIMB_BITS_IS_2_POW_B: () = assert!(LIMB_BITS == 1 << B);
388 debug_assert_eq!(r, t * (1 << B));
389 for _ in 0..B {
390 acc = elem_squared(acc, m);
391 }
392
393 Self(Elem {
394 limbs: acc.limbs,
395 encoding: PhantomData, })
397 }
398}
399
400impl<M> One<M, RRR> {
401 pub(crate) fn newRRR(One(oneRR): One<M, RR>, m: &Modulus<M>) -> Self {
402 Self(elem_squared(oneRR, m))
403 }
404}
405
406impl<M, E> AsRef<Elem<M, E>> for One<M, E> {
407 fn as_ref(&self) -> &Elem<M, E> {
408 &self.0
409 }
410}
411
412impl<M: PublicModulus, E> One<M, E> {
413 pub fn clone_into(&self, out: Storage<M>) -> Self {
414 Self(self.0.clone_into(out))
415 }
416}
417
418pub(crate) fn elem_exp_vartime<M>(
428 out: Storage<M>,
429 base: Elem<M, R>,
430 exponent: NonZeroU64,
431 m: &Modulus<M>,
432) -> Elem<M, R> {
433 let exponent = exponent.get();
451 let mut acc = base.clone_into(out);
452 let mut bit = 1 << (64 - 1 - exponent.leading_zeros());
453 debug_assert!((exponent & bit) != 0);
454 while bit > 1 {
455 bit >>= 1;
456 acc = elem_squared(acc, m);
457 if (exponent & bit) != 0 {
458 acc = elem_mul(&base, acc, m);
459 }
460 }
461 acc
462}
463
464pub fn elem_exp_consttime<N, P>(
465 out: Storage<P>,
466 base: &Elem<N>,
467 oneRRR: &One<P, RRR>,
468 exponent: &PrivateExponent,
469 p: &Modulus<P>,
470 other_prime_len_bits: BitLength,
471) -> Result<Elem<P, Unencoded>, LimbSliceError> {
472 elem_exp_consttime_inner::<N, P, { ELEM_EXP_CONSTTIME_MAX_MODULUS_LIMBS * STORAGE_ENTRIES }>(
475 out,
476 base,
477 oneRRR,
478 exponent,
479 p,
480 other_prime_len_bits,
481 )
482}
483
484const ELEM_EXP_CONSTTIME_MAX_MODULUS_LIMBS: usize = 2048 / LIMB_BITS;
487const _LIMBS_PER_CHUNK_DIVIDES_ELEM_EXP_CONSTTIME_MAX_MODULUS_LIMBS: () =
488 assert!(ELEM_EXP_CONSTTIME_MAX_MODULUS_LIMBS % limbs512::LIMBS_PER_CHUNK == 0);
489const WINDOW_BITS: u32 = 5;
490const TABLE_ENTRIES: usize = 1 << WINDOW_BITS;
491const STORAGE_ENTRIES: usize = TABLE_ENTRIES + if cfg!(target_arch = "x86_64") { 3 } else { 0 };
492
493#[cfg(not(target_arch = "x86_64"))]
494fn elem_exp_consttime_inner<N, M, const STORAGE_LIMBS: usize>(
495 out: Storage<M>,
496 base_mod_n: &Elem<N>,
497 oneRRR: &One<M, RRR>,
498 exponent: &PrivateExponent,
499 m: &Modulus<M>,
500 other_prime_len_bits: BitLength,
501) -> Result<Elem<M, Unencoded>, LimbSliceError> {
502 use crate::{bssl, limb::Window};
503
504 let base_rinverse: Elem<M, RInverse> = elem_reduced(out, base_mod_n, m, other_prime_len_bits);
505
506 let num_limbs = m.limbs().len();
507 let m_chunked: AsChunks<Limb, { limbs512::LIMBS_PER_CHUNK }> = match slice::as_chunks(m.limbs())
508 {
509 (m, []) => m,
510 _ => {
511 return Err(LimbSliceError::len_mismatch(LenMismatchError::new(
512 num_limbs,
513 )))
514 }
515 };
516 let cpe = m_chunked.len(); assert!(STORAGE_LIMBS % (STORAGE_ENTRIES * limbs512::LIMBS_PER_CHUNK) == 0); let mut table = limbs512::AlignedStorage::<STORAGE_LIMBS>::zeroed();
522 let mut table = table
523 .aligned_chunks_mut(TABLE_ENTRIES, cpe)
524 .map_err(LimbSliceError::len_mismatch)?;
525
526 let table = table.as_flattened_mut();
528
529 fn gather<M>(table: &[Limb], acc: &mut Elem<M, R>, i: Window) {
530 prefixed_extern! {
531 fn LIMBS_select_512_32(
532 r: *mut Limb,
533 table: *const Limb,
534 num_limbs: c::size_t,
535 i: Window,
536 ) -> bssl::Result;
537 }
538 Result::from(unsafe {
539 LIMBS_select_512_32(acc.limbs.as_mut_ptr(), table.as_ptr(), acc.limbs.len(), i)
540 })
541 .unwrap();
542 }
543
544 fn power<M>(
545 table: &[Limb],
546 mut acc: Elem<M, R>,
547 m: &Modulus<M>,
548 i: Window,
549 mut tmp: Elem<M, R>,
550 ) -> (Elem<M, R>, Elem<M, R>) {
551 for _ in 0..WINDOW_BITS {
552 acc = elem_squared(acc, m);
553 }
554 gather(table, &mut tmp, i);
555 let acc = elem_mul(&tmp, acc, m);
556 (acc, tmp)
557 }
558
559 fn entry(table: &[Limb], i: usize, num_limbs: usize) -> &[Limb] {
560 &table[(i * num_limbs)..][..num_limbs]
561 }
562 fn entry_mut(table: &mut [Limb], i: usize, num_limbs: usize) -> &mut [Limb] {
563 &mut table[(i * num_limbs)..][..num_limbs]
564 }
565
566 m.oneR(entry_mut(table, 0, num_limbs));
568
569 limbs_mul_mont(
571 (
572 entry_mut(table, 1, num_limbs),
573 base_rinverse.limbs.as_ref(),
574 oneRRR.as_ref().limbs.as_ref(),
575 ),
576 m.limbs(),
577 m.n0(),
578 m.cpu_features(),
579 )?;
580 for i in 2..TABLE_ENTRIES {
581 let (src1, src2) = if i % 2 == 0 {
582 (i / 2, i / 2)
583 } else {
584 (i - 1, 1)
585 };
586 let (previous, rest) = table.split_at_mut(num_limbs * i);
587 let src1 = entry(previous, src1, num_limbs);
588 let src2 = entry(previous, src2, num_limbs);
589 let dst = entry_mut(rest, 0, num_limbs);
590 limbs_mul_mont((dst, src1, src2), m.limbs(), m.n0(), m.cpu_features())?;
591 }
592
593 let mut acc = Elem {
594 limbs: base_rinverse.limbs,
595 encoding: PhantomData,
596 };
597 let tmp = m.alloc_zero();
598 let tmp = Elem {
599 limbs: tmp.limbs,
600 encoding: PhantomData,
601 };
602 let (acc, _) = limb::fold_5_bit_windows(
603 exponent.limbs(),
604 |initial_window| {
605 gather(&table, &mut acc, initial_window);
606 (acc, tmp)
607 },
608 |(acc, tmp), window| power(&table, acc, m, window, tmp),
609 );
610
611 Ok(acc.into_unencoded(m))
612}
613
614#[cfg(target_arch = "x86_64")]
615fn elem_exp_consttime_inner<N, M, const STORAGE_LIMBS: usize>(
616 out: Storage<M>,
617 base_mod_n: &Elem<N>,
618 oneRRR: &One<M, RRR>,
619 exponent: &PrivateExponent,
620 m: &Modulus<M>,
621 other_prime_len_bits: BitLength,
622) -> Result<Elem<M, Unencoded>, LimbSliceError> {
623 use super::limbs::x86_64::mont::{
624 gather5, mul_mont5, mul_mont_gather5_amm, power5_amm, scatter5, sqr_mont5,
625 };
626 use crate::{
627 cpu::{
628 intel::{Adx, Bmi2},
629 GetFeature as _,
630 },
631 limb::{LeakyWindow, Window},
632 polyfill::slice::AsChunksMut,
633 };
634
635 let n0 = m.n0();
636
637 let cpu2 = m.cpu_features().get_feature();
638 let cpu3 = m.cpu_features().get_feature();
639
640 if base_mod_n.limbs.len() != m.limbs().len() * 2 {
641 return Err(LimbSliceError::len_mismatch(LenMismatchError::new(
642 base_mod_n.limbs.len(),
643 )));
644 }
645
646 let m_original: AsChunks<Limb, 8> = match slice::as_chunks(m.limbs()) {
647 (m, []) => m,
648 _ => return Err(LimbSliceError::len_mismatch(LenMismatchError::new(8))),
649 };
650 let cpe = m_original.len(); let oneRRR = &oneRRR.as_ref().limbs;
653 let oneRRR = match slice::as_chunks(oneRRR) {
654 (c, []) => c,
655 _ => {
656 return Err(LimbSliceError::len_mismatch(LenMismatchError::new(
657 oneRRR.len(),
658 )))
659 }
660 };
661
662 const MOD_EXP_CTIME_ALIGN: usize = 64;
677 const _TABLE_ENTRIES_IS_32: () = assert!(TABLE_ENTRIES == 32);
679 const _STORAGE_ENTRIES_HAS_3_EXTRA: () = assert!(STORAGE_ENTRIES == TABLE_ENTRIES + 3);
680
681 assert!(STORAGE_LIMBS % (STORAGE_ENTRIES * limbs512::LIMBS_PER_CHUNK) == 0); let mut table = limbs512::AlignedStorage::<STORAGE_LIMBS>::zeroed();
683 let mut table = table
684 .aligned_chunks_mut(STORAGE_ENTRIES, cpe)
685 .map_err(LimbSliceError::len_mismatch)?;
686 let (mut table, mut state) = table.split_at_mut(TABLE_ENTRIES * cpe);
687 assert_eq!((table.as_ptr() as usize) % MOD_EXP_CTIME_ALIGN, 0);
688
689 let (mut acc, mut rest) = state.split_at_mut(cpe);
691 let (mut base_cached, mut m_cached) = rest.split_at_mut(cpe);
692
693 m_cached
695 .as_flattened_mut()
696 .copy_from_slice(m_original.as_flattened());
697 let m_cached = m_cached.as_ref();
698
699 let out: Elem<M, RInverse> = elem_reduced(out, base_mod_n, m, other_prime_len_bits);
700 let base_rinverse = match slice::as_chunks(&out.limbs) {
701 (c, []) => c,
702 _ => {
703 return Err(LimbSliceError::len_mismatch(LenMismatchError::new(
704 out.limbs.len(),
705 )))
706 }
707 };
708
709 mul_mont5(
711 base_cached.as_mut(),
712 base_rinverse,
713 oneRRR,
714 m_cached,
715 n0,
716 cpu2,
717 )?;
718 let base_cached = base_cached.as_ref();
719 let mut out = Storage::from(out); fn scatter_powers_of_2(
724 mut table: AsChunksMut<Limb, 8>,
725 mut acc: AsChunksMut<Limb, 8>,
726 m_cached: AsChunks<Limb, 8>,
727 n0: &N0,
728 mut i: LeakyWindow,
729 cpu: Option<(Adx, Bmi2)>,
730 ) -> Result<(), LimbSliceError> {
731 loop {
732 scatter5(acc.as_ref(), table.as_mut(), i)?;
733 i *= 2;
734 if i >= TABLE_ENTRIES as LeakyWindow {
735 break;
736 }
737 sqr_mont5(acc.as_mut(), m_cached, n0, cpu)?;
738 }
739 Ok(())
740 }
741
742 m.oneR(acc.as_flattened_mut());
746 scatter5(acc.as_ref(), table.as_mut(), 0)?;
747
748 acc.as_flattened_mut()
750 .copy_from_slice(base_cached.as_flattened());
751
752 scatter_powers_of_2(table.as_mut(), acc.as_mut(), m_cached, n0, 1, cpu2)?;
754 for i in (3..(TABLE_ENTRIES as LeakyWindow)).step_by(2) {
757 let power = Window::from(i - 1);
758 assert!(power < 32); unsafe {
760 mul_mont_gather5_amm(
761 acc.as_mut(),
762 base_cached,
763 table.as_ref(),
764 m_cached,
765 n0,
766 power,
767 cpu3,
768 )
769 }?;
770 scatter_powers_of_2(table.as_mut(), acc.as_mut(), m_cached, n0, i, cpu2)?;
771 }
772
773 let table = table.as_ref();
774
775 let acc = limb::fold_5_bit_windows(
776 exponent.limbs(),
777 |initial_window| {
778 unsafe { gather5(acc.as_mut(), table, initial_window) }
779 .unwrap_or_else(unwrap_impossible_limb_slice_error);
780 acc
781 },
782 |mut acc, window| {
783 unsafe { power5_amm(acc.as_mut(), table, m_cached, n0, window, cpu3) }
784 .unwrap_or_else(unwrap_impossible_limb_slice_error);
785 acc
786 },
787 );
788
789 out.limbs.copy_from_slice(acc.as_flattened());
791 Ok(from_montgomery_amm(out, m))
792}
793
794pub fn verify_inverses_consttime<M>(
796 a: &Elem<M, R>,
797 b: Elem<M, Unencoded>,
798 m: &Modulus<M>,
799) -> Result<(), error::Unspecified> {
800 let r = elem_mul(a, b, m);
801 limb::verify_limbs_equal_1_leak_bit(&r.limbs)
802}
803
804#[inline]
805pub fn elem_verify_equal_consttime<M, E>(
806 a: &Elem<M, E>,
807 b: &Elem<M, E>,
808) -> Result<(), error::Unspecified> {
809 let equal = limb::limbs_equal_limbs_consttime(&a.limbs, &b.limbs)
810 .unwrap_or_else(unwrap_impossible_len_mismatch_error);
811 if !equal.leak() {
812 return Err(error::Unspecified);
813 }
814 Ok(())
815}
816
817#[cold]
818#[inline(never)]
819fn unwrap_impossible_len_mismatch_error<T>(LenMismatchError { .. }: LenMismatchError) -> T {
820 unreachable!()
821}
822
823#[cold]
824#[inline(never)]
825fn unwrap_impossible_limb_slice_error(err: LimbSliceError) {
826 match err {
827 LimbSliceError::LenMismatch(_) => unreachable!(),
828 LimbSliceError::TooShort(_) => unreachable!(),
829 LimbSliceError::TooLong(_) => unreachable!(),
830 }
831}
832
833#[cfg(test)]
834mod tests {
835 use super::*;
836 use crate::cpu;
837 use crate::testutil as test;
838
839 struct M {}
841
842 impl PublicModulus for M {}
843
844 #[test]
845 fn test_elem_exp_consttime() {
846 let cpu_features = cpu::features();
847 test::run(
848 test_vector_file!("../../crypto/fipsmodule/bn/test/mod_exp_tests.txt"),
849 |section, test_case| {
850 assert_eq!(section, "");
851
852 let m = consume_modulus::<M>(test_case, "M");
853 let m = m.modulus(cpu_features);
854 let expected_result = consume_elem(test_case, "ModExp", &m);
855 let base = consume_elem(test_case, "A", &m);
856 let e = {
857 let bytes = test_case.consume_bytes("E");
858 PrivateExponent::from_be_bytes_for_test_only(untrusted::Input::from(&bytes), &m)
859 .expect("valid exponent")
860 };
861
862 let oneRR = One::newRR(m.alloc_zero(), &m);
863 let oneRRR = One::newRRR(oneRR, &m);
864
865 struct N {}
870 let other_modulus_len_bits = m.len_bits();
871 let base: Elem<N> = {
872 let mut limbs = BoxedLimbs::zero(base.limbs.len() * 2);
873 limbs[..base.limbs.len()].copy_from_slice(&base.limbs);
874 Elem {
875 limbs,
876 encoding: PhantomData,
877 }
878 };
879
880 let too_big = m.limbs().len() > ELEM_EXP_CONSTTIME_MAX_MODULUS_LIMBS;
881 let actual_result = if !too_big {
882 elem_exp_consttime(
883 m.alloc_zero(),
884 &base,
885 &oneRRR,
886 &e,
887 &m,
888 other_modulus_len_bits,
889 )
890 } else {
891 let actual_result = elem_exp_consttime(
892 m.alloc_zero(),
893 &base,
894 &oneRRR,
895 &e,
896 &m,
897 other_modulus_len_bits,
898 );
899 assert!(actual_result.is_err());
901 elem_exp_consttime_inner::<_, _, { (4096 / LIMB_BITS) * STORAGE_ENTRIES }>(
903 m.alloc_zero(),
904 &base,
905 &oneRRR,
906 &e,
907 &m,
908 other_modulus_len_bits,
909 )
910 };
911 match actual_result {
912 Ok(r) => assert_elem_eq(&r, &expected_result),
913 Err(LimbSliceError::LenMismatch { .. }) => panic!(),
914 Err(LimbSliceError::TooLong { .. }) => panic!(),
915 Err(LimbSliceError::TooShort { .. }) => panic!(),
916 };
917
918 Ok(())
919 },
920 )
921 }
922
923 #[test]
928 fn test_elem_mul() {
929 let cpu_features = cpu::features();
930 test::run(
931 test_vector_file!("../../crypto/fipsmodule/bn/test/mod_mul_tests.txt"),
932 |section, test_case| {
933 assert_eq!(section, "");
934
935 let m = consume_modulus::<M>(test_case, "M");
936 let m = m.modulus(cpu_features);
937 let expected_result = consume_elem(test_case, "ModMul", &m);
938 let a = consume_elem(test_case, "A", &m);
939 let b = consume_elem(test_case, "B", &m);
940
941 let b = into_encoded(m.alloc_zero(), b, &m);
942 let a = into_encoded(m.alloc_zero(), a, &m);
943 let actual_result = elem_mul(&a, b, &m);
944 let actual_result = actual_result.into_unencoded(&m);
945 assert_elem_eq(&actual_result, &expected_result);
946
947 Ok(())
948 },
949 )
950 }
951
952 #[test]
953 fn test_elem_squared() {
954 let cpu_features = cpu::features();
955 test::run(
956 test_vector_file!("bigint_elem_squared_tests.txt"),
957 |section, test_case| {
958 assert_eq!(section, "");
959
960 let m = consume_modulus::<M>(test_case, "M");
961 let m = m.modulus(cpu_features);
962 let expected_result = consume_elem(test_case, "ModSquare", &m);
963 let a = consume_elem(test_case, "A", &m);
964
965 let a = into_encoded(m.alloc_zero(), a, &m);
966 let actual_result = elem_squared(a, &m);
967 let actual_result = actual_result.into_unencoded(&m);
968 assert_elem_eq(&actual_result, &expected_result);
969
970 Ok(())
971 },
972 )
973 }
974
975 #[test]
976 fn test_elem_reduced() {
977 let cpu_features = cpu::features();
978 test::run(
979 test_vector_file!("bigint_elem_reduced_tests.txt"),
980 |section, test_case| {
981 assert_eq!(section, "");
982
983 struct M {}
984
985 let m_ = consume_modulus::<M>(test_case, "M");
986 let m = m_.modulus(cpu_features);
987 let expected_result = consume_elem(test_case, "R", &m);
988 let a =
989 consume_elem_unchecked::<M>(test_case, "A", expected_result.limbs.len() * 2);
990 let other_modulus_len_bits = m_.len_bits();
991
992 let actual_result = elem_reduced(m.alloc_zero(), &a, &m, other_modulus_len_bits);
993 let oneRR = One::newRR(m.alloc_zero(), &m);
994 let actual_result = elem_mul(oneRR.as_ref(), actual_result, &m);
995 assert_elem_eq(&actual_result, &expected_result);
996
997 Ok(())
998 },
999 )
1000 }
1001
1002 #[test]
1003 fn test_elem_reduced_once() {
1004 let cpu_features = cpu::features();
1005 test::run(
1006 test_vector_file!("bigint_elem_reduced_once_tests.txt"),
1007 |section, test_case| {
1008 assert_eq!(section, "");
1009
1010 struct M {}
1011 struct O {}
1012 let m = consume_modulus::<M>(test_case, "m");
1013 let m = m.modulus(cpu_features);
1014 let a = consume_elem_unchecked::<O>(test_case, "a", m.limbs().len());
1015 let expected_result = consume_elem::<M>(test_case, "r", &m);
1016 let other_modulus_len_bits = m.len_bits();
1017
1018 let actual_result =
1019 elem_reduced_once(m.alloc_zero(), &a, &m, other_modulus_len_bits);
1020 assert_elem_eq(&actual_result, &expected_result);
1021
1022 Ok(())
1023 },
1024 )
1025 }
1026
1027 fn consume_elem<M>(
1028 test_case: &mut test::TestCase,
1029 name: &str,
1030 m: &Modulus<M>,
1031 ) -> Elem<M, Unencoded> {
1032 let value = test_case.consume_bytes(name);
1033 Elem::from_be_bytes_padded(untrusted::Input::from(&value), m).unwrap()
1034 }
1035
1036 fn consume_elem_unchecked<M>(
1037 test_case: &mut test::TestCase,
1038 name: &str,
1039 num_limbs: usize,
1040 ) -> Elem<M, Unencoded> {
1041 let bytes = test_case.consume_bytes(name);
1042 let mut limbs = BoxedLimbs::zero(num_limbs);
1043 limb::parse_big_endian_and_pad_consttime(untrusted::Input::from(&bytes), &mut limbs)
1044 .unwrap();
1045 Elem {
1046 limbs,
1047 encoding: PhantomData,
1048 }
1049 }
1050
1051 fn consume_modulus<M>(test_case: &mut test::TestCase, name: &str) -> OwnedModulus<M> {
1052 let value = test_case.consume_bytes(name);
1053 OwnedModulus::from(
1054 OwnedModulusValue::from_be_bytes(untrusted::Input::from(&value)).unwrap(),
1055 )
1056 }
1057
1058 fn assert_elem_eq<M, E>(a: &Elem<M, E>, b: &Elem<M, E>) {
1059 if elem_verify_equal_consttime(a, b).is_err() {
1060 panic!("{:x?} != {:x?}", &*a.limbs, &*b.limbs);
1061 }
1062 }
1063
1064 fn into_encoded<M>(out: Storage<M>, a: Elem<M, Unencoded>, m: &Modulus<M>) -> Elem<M, R> {
1065 let oneRR = One::newRR(out, m);
1066 elem_mul(oneRR.as_ref(), a, m)
1067 }
1068}