@@ -67,12 +67,20 @@ impl PartialEq for P256Scalar {
6767impl Eq for P256Scalar { }
6868
6969impl P256Scalar {
70- pub const SCALAR_LENGTH : usize = 32 ;
70+ pub const LENGTH : usize = 32 ;
7171}
7272
73- impl Seedable < { Self :: SCALAR_LENGTH } > for P256Scalar {
74- fn from_seed ( seed : & Secret < { Self :: SCALAR_LENGTH } > ) -> Self {
75- Self ( BigNum :: from_slice ( & * * seed) )
73+ impl Seedable < { Self :: LENGTH } > for P256Scalar {
74+ fn from_seed ( seed : & Secret < { Self :: LENGTH } > ) -> Self {
75+ let from_seed = |seed : & Secret < { Self :: LENGTH } > | {
76+ let n = BigNum :: from_slice ( & * * seed) ?;
77+ let mut ctxt = BigNumContext :: new ( ) ?;
78+ let mut res = BigNum :: new ( ) ?;
79+ let order = get_group_order ( & mut ctxt) ?;
80+ res. nnmod ( & n, & order, & mut ctxt) ?;
81+ Ok ( res)
82+ } ;
83+ Self ( from_seed ( seed) )
7684 }
7785}
7886
@@ -219,20 +227,27 @@ impl Serializable for P256Scalar {
219227 type Error = CryptoCoreError ;
220228
221229 fn length ( & self ) -> usize {
222- Self :: SCALAR_LENGTH
230+ self . 0
231+ . as_ref ( )
232+ . map ( |n| n. to_vec ( ) . length ( ) )
233+ . unwrap_or_default ( )
223234 }
224235
225236 fn write ( & self , ser : & mut Serializer ) -> Result < usize , Self :: Error > {
226237 match & self . 0 {
227- Ok ( n) => ser. write_array ( & n. to_vec ( ) ) ,
238+ Ok ( n) => {
239+ let bytes = n. to_vec ( ) ;
240+ assert_eq ! ( bytes. len( ) , Self :: LENGTH ) ;
241+ ser. write_vec ( & n. to_vec ( ) )
242+ }
228243 Err ( e) => Err ( CryptoCoreError :: GenericSerializationError ( format ! (
229244 "cannot serialize a scalar in error state: {e}"
230245 ) ) ) ,
231246 }
232247 }
233248
234249 fn read ( de : & mut Deserializer ) -> Result < Self , Self :: Error > {
235- let bytes = de. read_array :: < 32 > ( ) ?;
250+ let bytes = de. read_vec ( ) ?;
236251 BigNum :: from_slice ( & bytes) . map ( Ok ) . map ( Self ) . map_err ( |e| {
237252 CryptoCoreError :: GenericDeserializationError ( format ! ( "cannot deserialize scalar: {e}" ) )
238253 } )
@@ -255,5 +270,11 @@ mod tests {
255270 let mut rng = CsRng :: from_entropy ( ) ;
256271 let s = P256Scalar :: random ( & mut rng) ;
257272 test_serialization ( & s) . unwrap ( ) ;
273+
274+ // Test serialization from seed.
275+ let mut rng = CsRng :: from_entropy ( ) ;
276+ let seed = Secret :: < { P256Scalar :: LENGTH } > :: random ( & mut rng) ;
277+ let s = P256Scalar :: from_seed ( & seed) ;
278+ test_serialization ( & s) . unwrap ( ) ;
258279 }
259280}
0 commit comments