@@ -6,6 +6,7 @@ use crate::{Components, PublicKey, Signature, DSA_OID};
6
6
use core:: cmp:: min;
7
7
use digest:: Digest ;
8
8
use num_bigint:: BigUint ;
9
+ use num_traits:: One ;
9
10
use pkcs8:: {
10
11
der:: { asn1:: UIntRef , AnyRef , Decode , Encode } ,
11
12
AlgorithmIdentifier , DecodePrivateKey , EncodePrivateKey , PrivateKeyInfo , SecretDocument ,
@@ -61,7 +62,11 @@ impl PrivateKey {
61
62
/// Check whether the private key is valid
62
63
#[ must_use]
63
64
pub fn is_valid ( & self ) -> bool {
64
- self . public_key ( ) . components ( ) . is_valid ( )
65
+ if !self . public_key ( ) . is_valid ( ) {
66
+ return false ;
67
+ }
68
+
69
+ * self . x ( ) >= BigUint :: one ( ) && self . x ( ) < self . public_key ( ) . components ( ) . q ( )
65
70
}
66
71
67
72
/// Sign data with the private key
@@ -120,7 +125,11 @@ impl<'a> TryFrom<PrivateKeyInfo<'a>> for PrivateKey {
120
125
value. algorithm . assert_algorithm_oid ( DSA_OID ) ?;
121
126
122
127
let parameters = value. algorithm . parameters_any ( ) ?;
123
- let components = parameters. decode_into ( ) ?;
128
+ let components: Components = parameters. decode_into ( ) ?;
129
+
130
+ if !components. is_valid ( ) {
131
+ return Err ( pkcs8:: Error :: KeyMalformed ) ;
132
+ }
124
133
125
134
let x = UIntRef :: from_der ( value. private_key ) ?;
126
135
let x = BigUint :: from_bytes_be ( x. as_bytes ( ) ) ;
@@ -133,7 +142,13 @@ impl<'a> TryFrom<PrivateKeyInfo<'a>> for PrivateKey {
133
142
} ;
134
143
135
144
let public_key = PublicKey :: from_components ( components, y) ;
136
- Ok ( PrivateKey :: from_components ( public_key, x) )
145
+ let private_key = PrivateKey :: from_components ( public_key, x) ;
146
+
147
+ if !private_key. is_valid ( ) {
148
+ return Err ( pkcs8:: Error :: KeyMalformed ) ;
149
+ }
150
+
151
+ Ok ( private_key)
137
152
}
138
153
}
139
154
0 commit comments