|
3 | 3 |
|
4 | 4 | use crate::interface_types::ecc::EccCurve;
|
5 | 5 | use crate::structures::{Public, RsaExponent};
|
| 6 | +use crate::utils::PublicKey as TpmPublicKey; |
6 | 7 | use crate::{Error, WrapperErrorKind};
|
7 | 8 |
|
8 | 9 | use core::convert::TryFrom;
|
@@ -144,6 +145,60 @@ impl TryFrom<&Public> for SubjectPublicKeyInfoOwned {
|
144 | 145 | }
|
145 | 146 | }
|
146 | 147 |
|
| 148 | +impl<C> TryFrom<&TpmPublicKey> for PublicKey<C> |
| 149 | +where |
| 150 | + C: CurveArithmetic + AssociatedTpmCurve, |
| 151 | + FieldBytesSize<C>: ModulusSize, |
| 152 | + AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>, |
| 153 | +{ |
| 154 | + type Error = Error; |
| 155 | + |
| 156 | + fn try_from(value: &TpmPublicKey) -> Result<Self, Self::Error> { |
| 157 | + match value { |
| 158 | + TpmPublicKey::Ecc { x, y } => { |
| 159 | + let x = x.as_slice(); |
| 160 | + let y = y.as_slice(); |
| 161 | + |
| 162 | + // TODO: When elliptic_curve bumps to 0.14, we can use the TryFrom implementation instead |
| 163 | + // of checking lengths manually |
| 164 | + if x.len() != FieldBytesSize::<C>::USIZE { |
| 165 | + return Err(Error::local_error(WrapperErrorKind::InvalidParam)); |
| 166 | + } |
| 167 | + if y.len() != FieldBytesSize::<C>::USIZE { |
| 168 | + return Err(Error::local_error(WrapperErrorKind::InvalidParam)); |
| 169 | + } |
| 170 | + |
| 171 | + let encoded_point = |
| 172 | + EncodedPoint::<C>::from_affine_coordinates(x.into(), y.into(), false); |
| 173 | + let public_key = PublicKey::<C>::try_from(&encoded_point) |
| 174 | + .map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?; |
| 175 | + |
| 176 | + Ok(public_key) |
| 177 | + } |
| 178 | + _ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)), |
| 179 | + } |
| 180 | + } |
| 181 | +} |
| 182 | + |
| 183 | +impl TryFrom<&TpmPublicKey> for RsaPublicKey { |
| 184 | + type Error = Error; |
| 185 | + |
| 186 | + fn try_from(value: &TpmPublicKey) -> Result<Self, Self::Error> { |
| 187 | + match value { |
| 188 | + TpmPublicKey::Rsa(modulus) => { |
| 189 | + let exponent = BigUint::from(65537u32); |
| 190 | + let modulus = BigUint::from_bytes_be(modulus.as_slice()); |
| 191 | + |
| 192 | + let public_key = RsaPublicKey::new(modulus, exponent) |
| 193 | + .map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?; |
| 194 | + |
| 195 | + Ok(public_key) |
| 196 | + } |
| 197 | + _ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)), |
| 198 | + } |
| 199 | + } |
| 200 | +} |
| 201 | + |
147 | 202 | /// Provides the value of the curve used in this crate for the specific curve.
|
148 | 203 | pub trait AssociatedTpmCurve {
|
149 | 204 | /// Value of the curve when interacting with the TPM.
|
|
0 commit comments