Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

elliptic-curve: remove ToString and FromStr impls #1600

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 20 additions & 23 deletions elliptic-curve/src/jwk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,12 @@ use crate::{
secret_key::SecretKey,
Curve, Error, FieldBytes, FieldBytesSize, Result,
};
use alloc::{
borrow::ToOwned,
format,
string::{String, ToString},
};
use alloc::{borrow::ToOwned, format, string::String};
use base64ct::{Base64UrlUnpadded as Base64Url, Encoding};
use core::{
fmt::{self, Debug},
marker::PhantomData,
str::{self, FromStr},
str,
};
use serdect::serde::{de, ser, Deserialize, Serialize};
use zeroize::{Zeroize, ZeroizeOnDrop};
Expand Down Expand Up @@ -158,20 +154,15 @@ impl JwkEcKey {
{
self.try_into()
}
}

impl FromStr for JwkEcKey {
type Err = Error;

fn from_str(s: &str) -> Result<Self> {
/// Decode from JSON string.
pub fn from_json(s: &str) -> Result<Self> {
serde_json::from_str(s).map_err(|_| Error)
}
}

#[allow(clippy::to_string_trait_impl)]
impl ToString for JwkEcKey {
fn to_string(&self) -> String {
serde_json::to_string(self).expect("JWK encoding error")
/// Encode to JSON string.
pub fn to_json(&self) -> Result<String> {
serde_json::to_string(self).map_err(|_| Error)
}
}

Expand Down Expand Up @@ -613,7 +604,7 @@ mod tests {

#[test]
fn parse_private_key() {
let jwk = JwkEcKey::from_str(JWK_PRIVATE_KEY).unwrap();
let jwk = JwkEcKey::from_json(JWK_PRIVATE_KEY).unwrap();
assert_eq!(jwk.crv, "P-256");
assert_eq!(jwk.x, "gI0GAILBdu7T53akrFmMyGcsF3n5dO7MmwNBHKW5SV0");
assert_eq!(jwk.y, "SLW_xSffzlPWrHEVI30DHM_4egVwt3NQqeUD7nMFpps");
Expand All @@ -625,7 +616,7 @@ mod tests {

#[test]
fn parse_public_key() {
let jwk = JwkEcKey::from_str(JWK_PUBLIC_KEY).unwrap();
let jwk = JwkEcKey::from_json(JWK_PUBLIC_KEY).unwrap();
assert_eq!(jwk.crv, "P-256");
assert_eq!(jwk.x, "gI0GAILBdu7T53akrFmMyGcsF3n5dO7MmwNBHKW5SV0");
assert_eq!(jwk.y, "SLW_xSffzlPWrHEVI30DHM_4egVwt3NQqeUD7nMFpps");
Expand All @@ -634,27 +625,33 @@ mod tests {

#[test]
fn parse_unsupported() {
assert_eq!(JwkEcKey::from_str(UNSUPPORTED_JWK), Err(Error));
assert_eq!(JwkEcKey::from_json(UNSUPPORTED_JWK), Err(Error));
}

#[test]
fn serialize_private_key() {
let actual = JwkEcKey::from_str(JWK_PRIVATE_KEY).unwrap().to_string();
let actual = JwkEcKey::from_json(JWK_PRIVATE_KEY)
.unwrap()
.to_json()
.unwrap();
let expected: String = JWK_PRIVATE_KEY.split_whitespace().collect();
assert_eq!(actual, expected);
}

#[test]
fn serialize_public_key() {
let actual = JwkEcKey::from_str(JWK_PUBLIC_KEY).unwrap().to_string();
let actual = JwkEcKey::from_json(JWK_PUBLIC_KEY)
.unwrap()
.to_json()
.unwrap();
let expected: String = JWK_PUBLIC_KEY.split_whitespace().collect();
assert_eq!(actual, expected);
}

#[cfg(feature = "dev")]
#[test]
fn jwk_into_encoded_point() {
let jwk = JwkEcKey::from_str(JWK_PUBLIC_KEY).unwrap();
let jwk = JwkEcKey::from_json(JWK_PUBLIC_KEY).unwrap();
let point = jwk.to_encoded_point::<MockCurve>().unwrap();
let (x, y) = match point.coordinates() {
Coordinates::Uncompressed { x, y } => (x, y),
Expand All @@ -668,7 +665,7 @@ mod tests {
#[cfg(feature = "dev")]
#[test]
fn encoded_point_into_jwk() {
let jwk = JwkEcKey::from_str(JWK_PUBLIC_KEY).unwrap();
let jwk = JwkEcKey::from_json(JWK_PUBLIC_KEY).unwrap();
let point = jwk.to_encoded_point::<MockCurve>().unwrap();
let jwk2 = JwkEcKey::from_encoded_point::<MockCurve>(&point).unwrap();
assert_eq!(jwk, jwk2);
Expand Down
44 changes: 5 additions & 39 deletions elliptic-curve/src/public_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@ use crate::{JwkEcKey, JwkParameters};
#[cfg(feature = "pkcs8")]
use pkcs8::spki::{AlgorithmIdentifier, AssociatedAlgorithmIdentifier, ObjectIdentifier};

#[cfg(feature = "pem")]
use core::str::FromStr;

#[cfg(feature = "sec1")]
use {
crate::{
Expand All @@ -32,13 +29,13 @@ use pkcs8::EncodePublicKey;
#[cfg(all(feature = "alloc", feature = "sec1"))]
use alloc::boxed::Box;

#[cfg(any(feature = "jwk", feature = "pem"))]
use alloc::string::{String, ToString};
#[cfg(feature = "jwk")]
use alloc::string::String;

#[cfg(feature = "serde")]
use serdect::serde::{de, ser, Deserialize, Serialize};

#[cfg(any(feature = "pem", feature = "serde"))]
#[cfg(feature = "serde")]
use pkcs8::DecodePublicKey;

#[cfg(all(feature = "sec1", feature = "pkcs8"))]
Expand Down Expand Up @@ -71,9 +68,6 @@ use {
/// [`elliptic_curve::pkcs8::DecodePublicKey`][`pkcs8::DecodePublicKey`]
/// trait to parse it.
///
/// When the `pem` feature of this crate (or a specific RustCrypto elliptic
/// curve crate) is enabled, a [`FromStr`] impl is also available.
///
/// # `serde` support
///
/// When the optional `serde` feature of this create is enabled, [`Serialize`]
Expand Down Expand Up @@ -181,7 +175,7 @@ where
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
FieldBytesSize<C>: ModulusSize,
{
jwk.parse::<JwkEcKey>().and_then(|jwk| Self::from_jwk(&jwk))
JwkEcKey::from_json(jwk).and_then(|jwk| Self::from_jwk(&jwk))
}

/// Serialize this public key as [`JwkEcKey`] JSON Web Key (JWK).
Expand All @@ -203,7 +197,7 @@ where
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
FieldBytesSize<C>: ModulusSize,
{
self.to_jwk().to_string()
self.to_jwk().to_json().expect("JWK encoding error")
}
}

Expand Down Expand Up @@ -488,34 +482,6 @@ where
}
}

#[cfg(feature = "pem")]
impl<C> FromStr for PublicKey<C>
where
C: AssociatedOid + CurveArithmetic,
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
FieldBytesSize<C>: ModulusSize,
{
type Err = Error;

fn from_str(s: &str) -> Result<Self> {
Self::from_public_key_pem(s).map_err(|_| Error)
}
}

#[cfg(feature = "pem")]
#[allow(clippy::to_string_trait_impl)]
impl<C> ToString for PublicKey<C>
where
C: AssociatedOid + CurveArithmetic,
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
FieldBytesSize<C>: ModulusSize,
{
fn to_string(&self) -> String {
self.to_public_key_pem(Default::default())
.expect("PEM encoding error")
}
}

#[cfg(feature = "serde")]
impl<C> Serialize for PublicKey<C>
where
Expand Down
12 changes: 3 additions & 9 deletions elliptic-curve/src/secret_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,8 @@ use {
#[cfg(all(feature = "arithmetic", any(feature = "jwk", feature = "pem")))]
use alloc::string::String;

#[cfg(all(feature = "arithmetic", feature = "jwk"))]
use alloc::string::ToString;

#[cfg(all(doc, feature = "pkcs8"))]
use {crate::pkcs8::DecodePrivateKey, core::str::FromStr};
use crate::pkcs8::DecodePrivateKey;

/// Elliptic curve secret keys.
///
Expand All @@ -71,9 +68,6 @@ use {crate::pkcs8::DecodePrivateKey, core::str::FromStr};
/// To decode an elliptic curve private key from PKCS#8, enable the `pkcs8`
/// feature of this crate (or the `pkcs8` feature of a specific RustCrypto
/// elliptic curve crate) and use the [`DecodePrivateKey`] trait to parse it.
///
/// When the `pem` feature of this crate (or a specific RustCrypto elliptic
/// curve crate) is enabled, a [`FromStr`] impl is also available.
#[derive(Clone)]
pub struct SecretKey<C: Curve> {
/// Scalar value
Expand Down Expand Up @@ -273,7 +267,7 @@ where
C: JwkParameters + ValidatePublicKey,
FieldBytesSize<C>: ModulusSize,
{
jwk.parse::<JwkEcKey>().and_then(|jwk| Self::from_jwk(&jwk))
JwkEcKey::from_json(jwk).and_then(|jwk| Self::from_jwk(&jwk))
}

/// Serialize this secret key as [`JwkEcKey`] JSON Web Key (JWK).
Expand All @@ -295,7 +289,7 @@ where
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
FieldBytesSize<C>: ModulusSize,
{
Zeroizing::new(self.to_jwk().to_string())
Zeroizing::new(self.to_jwk().to_json().expect("JWK encoding error"))
}
}

Expand Down
21 changes: 0 additions & 21 deletions elliptic-curve/src/secret_key/pkcs8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,6 @@ use {
pkcs8::{der, EncodePrivateKey},
};

// Imports for actual PEM support
#[cfg(feature = "pem")]
use {
crate::{error::Error, Result},
core::str::FromStr,
pkcs8::DecodePrivateKey,
};

impl<C> AssociatedAlgorithmIdentifier for SecretKey<C>
where
C: AssociatedOid + Curve,
Expand Down Expand Up @@ -75,16 +67,3 @@ where
Ok(der::SecretDocument::encode_msg(&pkcs8_key)?)
}
}

#[cfg(feature = "pem")]
impl<C> FromStr for SecretKey<C>
where
C: Curve + AssociatedOid + ValidatePublicKey,
FieldBytesSize<C>: ModulusSize,
{
type Err = Error;

fn from_str(s: &str) -> Result<Self> {
Self::from_pkcs8_pem(s).map_err(|_| Error)
}
}
2 changes: 1 addition & 1 deletion elliptic-curve/tests/pkcs8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ fn decode_pkcs8_public_key_from_der() {
#[test]
#[cfg(feature = "pem")]
fn decode_pkcs8_public_key_from_pem() {
let public_key = PKCS8_PUBLIC_KEY_PEM.parse::<PublicKey>().unwrap();
let public_key = PublicKey::from_public_key_pem(PKCS8_PUBLIC_KEY_PEM).unwrap();

// Ensure key parses equivalently to DER
let der_key = PublicKey::from_public_key_der(&PKCS8_PUBLIC_KEY_DER[..]).unwrap();
Expand Down
Loading