Rework Recipient to wrap p256::PublicKey

This commit is contained in:
Jack Grigg
2021-04-04 16:13:57 +12:00
parent a08f23a3e8
commit c7f173b43e
3 changed files with 18 additions and 24 deletions
+13 -19
View File
@@ -1,6 +1,5 @@
use bech32::{ToBase32, Variant};
use elliptic_curve::sec1::EncodedPoint;
use p256::NistP256;
use elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
use sha2::{Digest, Sha256};
use std::convert::TryInto;
use std::fmt;
@@ -11,11 +10,11 @@ pub(crate) const TAG_BYTES: usize = 4;
/// Wrapper around a compressed secp256r1 curve point.
#[derive(Clone)]
pub struct Recipient(EncodedPoint<NistP256>);
pub struct Recipient(p256::PublicKey);
impl fmt::Debug for Recipient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Recipient({:?})", self.as_bytes())
write!(f, "Recipient({:?})", self.to_encoded().as_bytes())
}
}
@@ -24,7 +23,7 @@ impl fmt::Display for Recipient {
f.write_str(
bech32::encode(
RECIPIENT_PREFIX,
self.as_bytes().to_base32(),
self.to_encoded().as_bytes().to_base32(),
Variant::Bech32,
)
.expect("HRP is valid")
@@ -34,22 +33,17 @@ impl fmt::Display for Recipient {
}
impl Recipient {
/// Attempts to parse a valid secp256r1 public key from its SEC-1 encoding.
pub(crate) fn from_pubkey(pubkey: EncodedPoint<NistP256>) -> Option<Self> {
if pubkey.is_compressed() {
if pubkey.decompress().is_some().into() {
Some(Recipient(pubkey))
} else {
None
}
} else {
Some(Recipient(pubkey.compress()))
}
/// Attempts to parse a valid YubiKey recipient from its SEC-1 encoding.
///
/// This accepts both compressed (as used by the plugin) and uncompressed (as used in
/// the YubiKey certificate) encodings.
pub(crate) fn from_encoded(encoded: &p256::EncodedPoint) -> Option<Self> {
p256::PublicKey::from_encoded_point(&encoded).map(Recipient)
}
/// Returns the compressed SEC-1 encoding of this public key.
pub(crate) fn as_bytes(&self) -> &[u8] {
self.0.as_bytes()
/// Returns the compressed SEC-1 encoding of this recipient.
pub(crate) fn to_encoded(&self) -> p256::EncodedPoint {
self.0.to_encoded_point(true)
}
pub(crate) fn tag(&self) -> [u8; TAG_BYTES] {