@@ -474,6 +474,28 @@ where
474474 }
475475}
476476
477+ #[ cfg( feature = "serde" ) ]
478+ impl < C > PublicKey < C >
479+ where
480+ C : AssociatedOid + CurveArithmetic ,
481+ AffinePoint < C > : FromEncodedPoint < C > + ToEncodedPoint < C > ,
482+ FieldBytesSize < C > : ModulusSize ,
483+ {
484+ /// Encode this [`PublicKey`] as der bytes, placing the result in `output`. This function
485+ /// returns a slice containing the encoded DER bytes.
486+ fn encode_as_der < ' buf > ( & self , output : & ' buf mut [ u8 ] ) -> der:: Result < & ' buf [ u8 ] > {
487+ let public_key_bytes = self . to_encoded_point ( false ) ;
488+ let subject_public_key = der:: asn1:: BitStringRef :: new ( 0 , public_key_bytes. as_bytes ( ) ) ?;
489+
490+ let spki = pkcs8:: SubjectPublicKeyInfo {
491+ algorithm : Self :: ALGORITHM_IDENTIFIER ,
492+ subject_public_key,
493+ } ;
494+
495+ der:: Encode :: encode_to_slice ( & spki, output)
496+ }
497+ }
498+
477499#[ cfg( all( feature = "alloc" , feature = "pkcs8" ) ) ]
478500impl < C > EncodePublicKey for PublicKey < C >
479501where
@@ -485,6 +507,7 @@ where
485507 let public_key_bytes = self . to_encoded_point ( false ) ;
486508 let subject_public_key = der:: asn1:: BitStringRef :: new ( 0 , public_key_bytes. as_bytes ( ) ) ?;
487509
510+ // TODO: use `encode_as_der` here?
488511 pkcs8:: SubjectPublicKeyInfo {
489512 algorithm : Self :: ALGORITHM_IDENTIFIER ,
490513 subject_public_key,
@@ -532,7 +555,11 @@ where
532555 where
533556 S : ser:: Serializer ,
534557 {
535- let der = self . to_public_key_der ( ) . map_err ( ser:: Error :: custom) ?;
558+ // TODO: can we determine DER encoding length up-front? Using `MockCurve` gives
559+ // 91 bytes of output, but it feels like that depends on the curve that is being
560+ // used here.
561+ let mut buf = [ 0u8 ; 91 ] ;
562+ let der = self . encode_as_der ( & mut buf) . map_err ( ser:: Error :: custom) ?;
536563 serdect:: slice:: serialize_hex_upper_or_bin ( & der, serializer)
537564 }
538565}
0 commit comments