Skip to content

Commit

Permalink
dsa: Update sanity checks
Browse files Browse the repository at this point in the history
  • Loading branch information
aumetra committed May 9, 2022
1 parent 1c33224 commit 8d7b70d
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 9 deletions.
11 changes: 6 additions & 5 deletions dsa/src/components.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use num_traits::One;
use pkcs8::der::{self, asn1::UIntRef, DecodeValue, Encode, Header, Reader, Sequence};
use rand::{CryptoRng, RngCore};

use crate::two;

/// The common components of an DSA keypair
///
/// (the prime p, quotient q and generator g)
Expand Down Expand Up @@ -63,11 +65,10 @@ impl Components {
/// Check whether the components are valid
#[must_use]
pub fn is_valid(&self) -> bool {
if *self.p() <= BigUint::one() || *self.q() <= BigUint::one() {
return false;
}

true
*self.p() >= two()
&& *self.q() >= two()
&& *self.g() >= BigUint::one()
&& self.g() < self.p()
}
}

Expand Down
15 changes: 13 additions & 2 deletions dsa/src/privatekey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::{Components, PublicKey, Signature, DSA_OID};
use core::cmp::min;
use digest::Digest;
use num_bigint::BigUint;
use num_traits::One;
use pkcs8::{
der::{asn1::UIntRef, AnyRef, Decode, Encode},
AlgorithmIdentifier, DecodePrivateKey, EncodePrivateKey, PrivateKeyInfo, SecretDocument,
Expand Down Expand Up @@ -61,7 +62,11 @@ impl PrivateKey {
/// Check whether the private key is valid
#[must_use]
pub fn is_valid(&self) -> bool {
self.public_key().components().is_valid()
if !self.public_key().is_valid() {
return false;
}

*self.x() >= BigUint::one() && self.x() < self.public_key().components().q()
}

/// Sign data with the private key
Expand Down Expand Up @@ -133,7 +138,13 @@ impl<'a> TryFrom<PrivateKeyInfo<'a>> for PrivateKey {
};

let public_key = PublicKey::from_components(components, y);
Ok(PrivateKey::from_components(public_key, x))
let private_key = PrivateKey::from_components(public_key, x);

if !private_key.is_valid() {
return Err(pkcs8::Error::KeyMalformed);
}

Ok(private_key)
}
}

Expand Down
4 changes: 2 additions & 2 deletions dsa/src/publickey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//! Module containing the definition of the public key container
//!

use crate::{Components, Signature, DSA_OID};
use crate::{two, Components, Signature, DSA_OID};
use core::cmp::min;
use digest::Digest;
use num_bigint::{BigUint, ModInverse};
Expand Down Expand Up @@ -52,7 +52,7 @@ impl PublicKey {
return false;
}

self.y().modpow(components.q(), components.p()) == BigUint::one()
*self.y() >= two() && self.y().modpow(components.q(), components.p()) == BigUint::one()
}

/// Verify if the signature matches the provided hash
Expand Down

0 comments on commit 8d7b70d

Please sign in to comment.