@@ -474,6 +474,28 @@ where
474
474
}
475
475
}
476
476
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
+
477
499
#[ cfg( all( feature = "alloc" , feature = "pkcs8" ) ) ]
478
500
impl < C > EncodePublicKey for PublicKey < C >
479
501
where
@@ -485,6 +507,7 @@ where
485
507
let public_key_bytes = self . to_encoded_point ( false ) ;
486
508
let subject_public_key = der:: asn1:: BitStringRef :: new ( 0 , public_key_bytes. as_bytes ( ) ) ?;
487
509
510
+ // TODO: use `encode_as_der` here?
488
511
pkcs8:: SubjectPublicKeyInfo {
489
512
algorithm : Self :: ALGORITHM_IDENTIFIER ,
490
513
subject_public_key,
@@ -532,7 +555,11 @@ where
532
555
where
533
556
S : ser:: Serializer ,
534
557
{
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) ?;
536
563
serdect:: slice:: serialize_hex_upper_or_bin ( & der, serializer)
537
564
}
538
565
}
0 commit comments