1use crate::{Encode, Error, Result, Writer};
4
5#[cfg(feature = "alloc")]
6pub use allocating::Mpint;
7
8#[derive(Clone, Copy, Debug)]
13pub struct MpintRef<'a>(&'a [u8]);
14
15impl<'a> MpintRef<'a> {
16 pub const MAX_SIZE: usize = 2048;
18
19 pub fn from_bytes(mut bytes: &'a [u8]) -> Result<Self> {
24 while let Some((0, rest)) = bytes.split_first() {
25 bytes = rest;
26 }
27 if bytes.len() > Self::MAX_SIZE {
28 return Err(Error::Length);
29 }
30 Ok(Self(bytes))
31 }
32
33 #[must_use]
35 pub fn as_bytes(&self) -> &'a [u8] {
36 self.0
37 }
38
39 fn needs_padding(&self) -> bool {
40 self.0.first().is_some_and(|byte| *byte >= 0x80)
41 }
42}
43
44impl Encode for MpintRef<'_> {
45 fn encoded_len(&self) -> Result<usize> {
46 Ok(4 + self.0.len() + usize::from(self.needs_padding()))
47 }
48
49 fn encode(&self, writer: &mut impl Writer) -> Result<()> {
50 let padding = self.needs_padding();
51 (self.0.len() + usize::from(padding)).encode(writer)?;
52 if padding {
53 0u8.encode(writer)?;
54 }
55 writer.write(self.0)
56 }
57}
58
59#[cfg(feature = "alloc")]
60mod allocating {
61 use super::MpintRef;
62 use crate::{Decode, Decoder, Encode, Error, Reader, Result, Writer};
63 use alloc::boxed::Box;
64 use core::fmt;
65
66 #[cfg(feature = "bigint")]
67 use crate::Uint;
68 #[cfg(feature = "zeroize")]
69 use zeroize::Zeroize;
70 #[cfg(feature = "ctutils")]
71 use {
72 core::cmp::Ordering,
73 ctutils::{Choice, CtEq, CtLt, CtSelect},
74 };
75
76 #[derive(Clone)]
105 #[cfg_attr(not(feature = "ctutils"), derive(Eq, PartialEq))]
106 pub struct Mpint {
107 inner: Box<[u8]>,
109 }
110
111 impl Mpint {
112 pub const MAX_SIZE: usize = MpintRef::MAX_SIZE;
116
117 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
126 let bytes = MpintRef::from_bytes(bytes)?.as_bytes();
127
128 let mut inner = crate::vec_with_reserve(bytes.len())?;
129 inner.extend_from_slice(bytes);
130
131 Ok(Self {
132 inner: inner.into_boxed_slice(),
133 })
134 }
135
136 #[must_use]
140 pub fn as_bytes(&self) -> &[u8] {
141 &self.inner
142 }
143
144 #[must_use]
146 pub fn is_zero(&self) -> bool {
147 self.inner.is_empty()
148 }
149 }
150
151 impl AsRef<[u8]> for Mpint {
152 fn as_ref(&self) -> &[u8] {
153 self.as_bytes()
154 }
155 }
156
157 #[cfg(feature = "ctutils")]
158 impl CtEq for Mpint {
159 fn ct_eq(&self, other: &Self) -> Choice {
160 self.as_bytes().ct_eq(other.as_bytes())
161 }
162 }
163
164 #[cfg(feature = "ctutils")]
165 impl Eq for Mpint {}
166
167 #[cfg(feature = "ctutils")]
168 impl PartialEq for Mpint {
169 fn eq(&self, other: &Self) -> bool {
170 self.ct_eq(other).into()
171 }
172 }
173
174 #[cfg(feature = "ctutils")]
175 impl Ord for Mpint {
176 fn cmp(&self, other: &Self) -> Ordering {
177 match self.inner.len().cmp(&other.inner.len()) {
179 Ordering::Equal => {}
180 ordering => return ordering,
181 }
182
183 let mut ordering = Ordering::Equal;
185 for (a, b) in self.inner.iter().zip(other.inner.iter()).rev() {
186 ordering = ordering.ct_select(&Ordering::Less, a.ct_lt(b));
187 ordering = ordering.ct_select(&Ordering::Greater, b.ct_lt(a));
188 }
189 ordering
190 }
191 }
192
193 #[cfg(feature = "ctutils")]
194 impl PartialOrd for Mpint {
195 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
196 Some(self.cmp(other))
197 }
198 }
199
200 impl Decode for Mpint {
201 type Error = Error;
202
203 fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
204 reader.read_prefixed(|reader| {
205 let Some(first) = reader.read_mpint_prefix()? else {
206 return Self::from_bytes(&[]);
207 };
208
209 let mut bytes = crate::vec_zeroed(reader.remaining_len() + 1)?;
210 bytes[0] = first;
211 reader.read(&mut bytes[1..])?;
212
213 Ok(Self {
214 inner: bytes.into_boxed_slice(),
215 })
216 })
217 }
218 }
219
220 impl Encode for Mpint {
221 fn encoded_len(&self) -> Result<usize> {
222 MpintRef::from(self).encoded_len()
223 }
224
225 fn encode(&self, writer: &mut impl Writer) -> Result<()> {
226 MpintRef::from(self).encode(writer)
227 }
228 }
229
230 impl<'a> From<&'a Mpint> for MpintRef<'a> {
231 fn from(mpint: &'a Mpint) -> Self {
232 Self(mpint.as_bytes())
233 }
234 }
235
236 impl TryFrom<&[u8]> for Mpint {
237 type Error = Error;
238
239 fn try_from(bytes: &[u8]) -> Result<Self> {
240 Self::from_bytes(bytes)
241 }
242 }
243
244 impl TryFrom<Box<[u8]>> for Mpint {
245 type Error = Error;
246
247 fn try_from(bytes: Box<[u8]>) -> Result<Self> {
248 if bytes.first() == Some(&0) {
249 let result = Self::from_bytes(&bytes);
250 #[cfg(feature = "zeroize")]
251 {
252 let mut bytes = bytes;
253 bytes.zeroize();
254 }
255 result
256 } else if bytes.len() > Self::MAX_SIZE {
257 Err(Error::Length)
258 } else {
259 Ok(Self { inner: bytes })
260 }
261 }
262 }
263
264 #[cfg(feature = "zeroize")]
265 impl Zeroize for Mpint {
266 fn zeroize(&mut self) {
267 self.inner.zeroize();
268 self.inner = Box::default();
270 }
271 }
272
273 impl fmt::Debug for Mpint {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 write!(f, "Mpint({self:X})")
276 }
277 }
278
279 impl fmt::Display for Mpint {
280 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281 write!(f, "{self:X}")
282 }
283 }
284
285 impl fmt::LowerHex for Mpint {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 if self.is_zero() {
288 return f.write_str("0");
289 }
290
291 for byte in self.as_bytes() {
292 write!(f, "{byte:02x}")?;
293 }
294
295 Ok(())
296 }
297 }
298
299 impl fmt::UpperHex for Mpint {
300 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301 if self.is_zero() {
302 return f.write_str("0");
303 }
304
305 for byte in self.as_bytes() {
306 write!(f, "{byte:02X}")?;
307 }
308
309 Ok(())
310 }
311 }
312
313 #[cfg(feature = "bigint")]
314 impl TryFrom<&Uint> for Mpint {
315 type Error = Error;
316
317 fn try_from(uint: &Uint) -> Result<Self> {
318 #[allow(deprecated, reason = "crypto-bigint v0.7.0 compatibility")]
321 let bits = uint.bits_vartime();
322
323 if bits > u32::try_from(Self::MAX_SIZE * 8)? {
324 return Err(Error::Length);
325 }
326
327 let mut inner = crate::vec_with_reserve(usize::try_from(bits.div_ceil(8))?)?;
329
330 for limb in uint.as_limbs().iter().rev() {
331 let bytes = limb.0.to_be_bytes();
332
333 let bytes = if inner.is_empty() {
334 MpintRef::from_bytes(&bytes)?.as_bytes()
335 } else {
336 &bytes
337 };
338
339 inner.extend_from_slice(bytes);
340 }
341
342 Ok(Self {
343 inner: inner.into_boxed_slice(),
344 })
345 }
346 }
347
348 #[cfg(feature = "bigint")]
349 impl TryFrom<Uint> for Mpint {
350 type Error = Error;
351
352 fn try_from(uint: Uint) -> Result<Self> {
353 Self::try_from(&uint)
354 }
355 }
356
357 #[cfg(feature = "bigint")]
358 impl From<Mpint> for Uint {
359 fn from(mpint: Mpint) -> Uint {
360 Uint::from(&mpint)
361 }
362 }
363
364 #[cfg(feature = "bigint")]
365 impl From<&Mpint> for Uint {
366 fn from(mpint: &Mpint) -> Uint {
367 Uint::from_be_slice_vartime(mpint.as_bytes())
368 }
369 }
370
371 #[cfg(test)]
372 mod tests {
373 use super::Mpint;
374 use crate::{Decode, Encode, Error, Reader};
375 use alloc::{format, vec, vec::Vec};
376 use hex_literal::hex;
377
378 #[test]
379 fn unsigned_bytes() {
380 for (bytes, expected) in [
381 (&b""[..], &b""[..]),
382 (&hex!("00")[..], &b""[..]),
383 (&hex!("00 00")[..], &b""[..]),
384 (&hex!("00 01")[..], &hex!("01")[..]),
385 (&hex!("00 00 80")[..], &hex!("80")[..]),
386 (&hex!("80")[..], &hex!("80")[..]),
387 (&hex!("ff")[..], &hex!("ff")[..]),
388 ] {
389 for n in [
390 Mpint::from_bytes(bytes).unwrap(),
391 Mpint::try_from(bytes).unwrap(),
392 Mpint::try_from(Vec::from(bytes).into_boxed_slice()).unwrap(),
393 ] {
394 assert_eq!(n.as_bytes(), expected);
395 assert_eq!(n.is_zero(), expected.is_empty());
396 }
397 }
398 }
399
400 #[test]
401 fn ssh_encodings() {
402 for (bytes, encoded) in [
403 (&b""[..], &hex!("00000000")[..]),
404 (&hex!("01")[..], &hex!("00000001 01")[..]),
405 (&hex!("7f")[..], &hex!("00000001 7f")[..]),
406 (&hex!("80")[..], &hex!("00000002 0080")[..]),
407 (&hex!("ff")[..], &hex!("00000002 00ff")[..]),
408 (
409 &hex!("09 a3 78 f9 b2 e3 32 a7")[..],
410 &hex!("00000008 09 a3 78 f9 b2 e3 32 a7")[..],
411 ),
412 ] {
413 let n = Mpint::from_bytes(bytes).unwrap();
414 let mut output = Vec::new();
415 n.encode(&mut output).unwrap();
416 assert_eq!(output, encoded);
417 assert_eq!(n.encoded_len().unwrap(), output.len());
418 assert_eq!(
419 Mpint::decode(&mut encoded.into_decoder().unwrap()).unwrap(),
420 n
421 );
422 }
423 }
424
425 #[test]
426 fn normalize_ssh_padding() {
427 for bytes in [
428 &hex!("00")[..],
429 &hex!("00 00")[..],
430 &hex!("00 01")[..],
431 &hex!("00 00 80")[..],
432 ] {
433 let mut encoded = Vec::new();
434 bytes.encode(&mut encoded).unwrap();
435 let n = Mpint::decode(&mut encoded.as_slice().into_decoder().unwrap()).unwrap();
436 assert_eq!(n, Mpint::from_bytes(bytes).unwrap());
437 let mut canonical = Vec::new();
438 n.encode(&mut canonical).unwrap();
439 assert!(canonical.len() < encoded.len());
440 }
441 }
442
443 #[test]
444 fn reject_negative() {
445 for bytes in [
446 &hex!("80")[..],
447 &hex!("ff")[..],
448 &hex!("ed cc")[..],
449 &hex!("ff 21 52 41 11")[..],
450 ] {
451 let mut encoded = Vec::new();
452 bytes.encode(&mut encoded).unwrap();
453 let mut reader = encoded.as_slice().into_decoder().unwrap();
454 assert_eq!(Mpint::decode(&mut reader), Err(Error::MpintEncoding));
455 assert_eq!(reader.finish(()), Err(Error::Failed));
456 }
457 }
458
459 #[test]
460 fn size_limits() {
461 for size in [Mpint::MAX_SIZE, Mpint::MAX_SIZE + 1] {
462 for first in [0x01, 0x7f, 0x80, 0xff] {
463 let mut bytes = vec![0xff; size];
464 bytes[0] = first;
465 for padding in [0, 1, 2] {
467 let mut padded = vec![0; padding];
468 padded.extend_from_slice(&bytes);
469 for result in [
470 Mpint::from_bytes(&padded),
471 Mpint::try_from(padded.clone().into_boxed_slice()),
472 ] {
473 if size == Mpint::MAX_SIZE {
474 let n = result.unwrap();
475 assert_eq!(n.as_bytes(), bytes);
476 let mut encoded = Vec::new();
477 n.encode(&mut encoded).unwrap();
478 assert_eq!(n.encoded_len().unwrap(), encoded.len());
479 assert_eq!(
480 Mpint::decode(&mut encoded.as_slice().into_decoder().unwrap())
481 .unwrap(),
482 n
483 );
484 } else {
485 assert_eq!(result, Err(Error::Length));
486 }
487 }
488 }
489 }
490 }
491 }
492
493 #[test]
494 fn ssh_size_limits_before_normalization() {
495 for (first, size, valid) in [
496 (0x7f, Mpint::MAX_SIZE, true),
497 (0x00, Mpint::MAX_SIZE + 1, true),
498 (0x01, Mpint::MAX_SIZE + 1, false),
499 (0x00, Mpint::MAX_SIZE + 2, false),
500 ] {
501 for rest in [0, 0xff] {
503 let mut bytes = vec![rest; size];
504 bytes[0] = first;
505 let mut encoded = Vec::new();
506 bytes.encode(&mut encoded).unwrap();
507 let result = Mpint::decode(&mut encoded.as_slice().into_decoder().unwrap());
508 if valid {
509 assert_eq!(result.unwrap(), Mpint::from_bytes(&bytes).unwrap());
510 } else {
511 assert_eq!(result, Err(Error::Length));
512 }
513 }
514 }
515 }
516
517 #[test]
518 fn reject_oversized_before_reading_body() {
519 struct Unreadable {
520 prefix: Option<[u8; 4]>,
521 }
522
523 impl Reader for Unreadable {
524 fn read<'o>(&mut self, out: &'o mut [u8]) -> crate::Result<&'o [u8]> {
525 let prefix = self
526 .prefix
527 .take()
528 .expect("oversized mpint body must not be read");
529 out.copy_from_slice(&prefix);
530 Ok(out)
531 }
532
533 fn remaining_len(&self) -> usize {
534 Mpint::MAX_SIZE + 2 + if self.prefix.is_some() { 4 } else { 0 }
535 }
536 }
537
538 let reader = Unreadable {
539 prefix: Some(u32::try_from(Mpint::MAX_SIZE + 2).unwrap().to_be_bytes()),
540 };
541 assert_eq!(
542 Mpint::decode(&mut reader.into_decoder().unwrap()),
543 Err(Error::Length)
544 );
545 }
546
547 #[test]
548 #[cfg(feature = "ctutils")]
549 fn numeric_ordering() {
550 let values = [
551 0u32, 1, 0x7f, 0x80, 0xff, 0x100, 0x101, 0x1ff, 0x200, 0xffff, 0x10000,
552 ];
553 for a in values {
554 for b in values {
555 let x = Mpint::from_bytes(&a.to_be_bytes()).unwrap();
556 let y = Mpint::from_bytes(&b.to_be_bytes()).unwrap();
557 assert_eq!(x == y, a == b);
558 assert_eq!(x.cmp(&y), a.cmp(&b));
559 assert_eq!(x.partial_cmp(&y), a.partial_cmp(&b));
560 }
561 }
562 }
563
564 #[test]
565 fn formatting() {
566 let zero = Mpint::from_bytes(&[]).unwrap();
567 assert_eq!(
568 format!("{zero} {zero:x} {zero:X} {zero:?}"),
569 "0 0 0 Mpint(0)"
570 );
571 let n = Mpint::from_bytes(&hex!("00 ab cd")).unwrap();
572 assert_eq!(
573 format!("{n} {n:x} {n:X} {n:?}"),
574 "ABCD abcd ABCD Mpint(ABCD)"
575 );
576 }
577
578 #[cfg(feature = "zeroize")]
579 #[test]
580 fn zeroize_preserves_invariants() {
581 use zeroize::Zeroize;
582 let mut n = Mpint::from_bytes(&hex!("80 ff")).unwrap();
583 n.zeroize();
584 assert!(n.is_zero());
585 assert_eq!(n, Mpint::from_bytes(&[]).unwrap());
586 let mut encoded = Vec::new();
587 n.encode(&mut encoded).unwrap();
588 assert_eq!(encoded, hex!("00000000"));
589 }
590
591 #[cfg(feature = "bigint")]
592 #[test]
593 fn bigint_conversions() {
594 use crate::Uint;
595 for bytes in [
596 vec![],
597 vec![0],
598 vec![0x80],
599 hex!("12 34 56 78 9a bc de f0 00 01").to_vec(),
600 vec![0xff; Mpint::MAX_SIZE],
601 vec![0xff; Mpint::MAX_SIZE + 1],
602 ] {
603 let uint = Uint::from_be_slice_vartime(&bytes);
604 for result in [Mpint::try_from(&uint), Mpint::try_from(uint.clone())] {
605 if bytes.len() <= Mpint::MAX_SIZE {
606 let n = result.unwrap();
607 assert_eq!(n, Mpint::from_bytes(&bytes).unwrap());
608 assert_eq!(Uint::from(&n), uint);
609 assert_eq!(Uint::from(n), uint);
610 } else {
611 assert_eq!(result, Err(Error::Length));
612 }
613 }
614 }
615 let mut padded = vec![0; Mpint::MAX_SIZE + 1];
617 padded[Mpint::MAX_SIZE] = 1;
618 let uint = Uint::from_be_slice_vartime(&padded);
619 assert_eq!(Mpint::try_from(&uint).unwrap().as_bytes(), &[1]);
620 }
621 }
622}
623
624#[cfg(test)]
625mod tests {
626 use super::MpintRef;
627 use crate::{Decoder, Encode, Error};
628
629 #[test]
630 fn decode_left_pads_and_encode_is_canonical() {
631 let mut out = [0xff; 2];
632 for (input, expected, canonical) in [
633 (&[0, 0, 0, 2, 0, 0][..], &[0, 0], &[0, 0, 0, 0][..]),
634 (&[0, 0, 0, 3, 0, 0, 1], &[0, 1], &[0, 0, 0, 1, 1]),
635 (
636 &[0, 0, 0, 3, 0, 0x80, 0],
637 &[0x80, 0],
638 &[0, 0, 0, 3, 0, 0x80, 0],
639 ),
640 ] {
641 let mut reader = Decoder::new(input).unwrap();
642 let magnitude = reader.read_mpint_bytes(&mut out).unwrap();
643 assert_eq!(
644 reader.finish(magnitude).unwrap(),
645 MpintRef::from_bytes(expected).unwrap().as_bytes()
646 );
647 assert_eq!(&out, expected);
648 let value = MpintRef::from_bytes(&out).unwrap();
649 let mut buf = [0; 7];
650 assert_eq!(value.encoded_len().unwrap(), canonical.len());
651 let mut writer = &mut buf[..canonical.len()];
652 value.encode(&mut writer).unwrap();
653 assert!(writer.is_empty());
654 assert_eq!(&buf[..canonical.len()], canonical);
655 }
656 }
657
658 #[test]
659 fn reject_negative_and_oversize_values() {
660 for (input, error) in [
661 (&[0, 0, 0, 1, 0x80][..], Error::MpintEncoding),
662 (&[0, 0, 0, 2, 1, 0], Error::Length),
663 ] {
664 let mut reader = Decoder::new(input).unwrap();
665 assert_eq!(reader.read_mpint_bytes(&mut [0]), Err(error));
666 assert_eq!(reader.finish(()), Err(Error::Failed));
667 }
668 }
669}