Skip to content

Commit a93ca2b

Browse files
committed
PublicKeyParts: provide serialization helpers
When serializing the exponent or the modulus from a key, `BoxedUint::to_be_bytes` will return a slice padded with zeroes on the left because of its inner representation. Not every implementation out there will handle leading zeroes. This provides a `PublicKeyParts::n_bytes`/`n_bytes` that will strip out those leading zeros.
1 parent b831df8 commit a93ca2b

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

src/key.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,8 @@ mod tests {
718718
let n_limbs: &[u64] = PublicKeyParts::n(&public_key).as_ref().as_ref();
719719
assert_eq!(n_limbs, &[101u64]);
720720
assert_eq!(PublicKeyParts::e(&public_key), &BoxedUint::from(200u64));
721+
assert_eq!(PublicKeyParts::e_bytes(&public_key), [200].into());
722+
assert_eq!(PublicKeyParts::n_bytes(&public_key), [101].into());
721723
}
722724

723725
fn test_key_basics(private_key: &RsaPrivateKey) {

src/traits/keys.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! Traits related to the key components
22
3+
use alloc::boxed::Box;
34
use crypto_bigint::{
45
modular::{BoxedMontyForm, BoxedMontyParams},
56
BoxedUint, NonZero,
@@ -27,6 +28,22 @@ pub trait PublicKeyParts {
2728
fn n_bits_precision(&self) -> u32 {
2829
self.n().bits_precision()
2930
}
31+
32+
/// Returns the big endian serialization of the modulus of the key
33+
fn n_bytes(&self) -> Box<[u8]> {
34+
let modulus = self.n();
35+
let modulus_zeros = modulus.leading_zeros() as usize / 8;
36+
let modulus = modulus.to_be_bytes();
37+
(&modulus[modulus_zeros..]).into()
38+
}
39+
40+
/// Returns the big endian serialization of the public exponent of the key
41+
fn e_bytes(&self) -> Box<[u8]> {
42+
let exponent = self.e();
43+
let exponent_zeros = exponent.leading_zeros() as usize / 8;
44+
let exponent = exponent.to_be_bytes();
45+
(&exponent[exponent_zeros..]).into()
46+
}
3047
}
3148

3249
/// Components of an RSA private key.

0 commit comments

Comments
 (0)