From 46616efc904e0f0730d21d23afd1f0e9b7702d2a Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Mon, 3 Aug 2020 15:47:33 -0700 Subject: [PATCH] elliptic-curve: add weierstrass::PublicKey::compress Generic point compression support for SEC-1 encoded public keys --- elliptic-curve/src/weierstrass/point.rs | 10 ++++++++++ elliptic-curve/src/weierstrass/public_key.rs | 9 +++++++++ 2 files changed, 19 insertions(+) diff --git a/elliptic-curve/src/weierstrass/point.rs b/elliptic-curve/src/weierstrass/point.rs index 735ceb711..e0d6c30a0 100644 --- a/elliptic-curve/src/weierstrass/point.rs +++ b/elliptic-curve/src/weierstrass/point.rs @@ -171,6 +171,16 @@ where pub fn into_bytes(self) -> GenericArray> { self.bytes } + + /// Get the x-coordinate of this curve point + pub(crate) fn x(&self) -> &ScalarBytes { + GenericArray::from_slice(&self.bytes[1..(C::ElementSize::to_usize() + 1)]) + } + + /// Get the y-coordinate of this curve point + pub(crate) fn y(&self) -> &ScalarBytes { + GenericArray::from_slice(&self.bytes[(C::ElementSize::to_usize() + 1)..]) + } } impl AsRef<[u8]> for UncompressedPoint diff --git a/elliptic-curve/src/weierstrass/public_key.rs b/elliptic-curve/src/weierstrass/public_key.rs index 796a0b866..ef01f02b9 100644 --- a/elliptic-curve/src/weierstrass/public_key.rs +++ b/elliptic-curve/src/weierstrass/public_key.rs @@ -99,6 +99,15 @@ where PublicKey::Uncompressed(UncompressedPoint::from_bytes(tagged_bytes).unwrap()) } + /// Compress this [`PublicKey`]. + /// + /// If the key is already compressed, this is a no-op. + pub fn compress(&mut self) { + if let PublicKey::Uncompressed(point) = self { + *self = CompressedPoint::from_affine_coords(point.x(), point.y()).into(); + } + } + /// Obtain public key as a byte array reference #[inline] pub fn as_bytes(&self) -> &[u8] {