From 4362f11288b1c5abd7c9c31b094e19e9f035ede5 Mon Sep 17 00:00:00 2001 From: Peter Dettman Date: Sat, 10 Jun 2017 18:30:41 +0700 Subject: Checks on DH peer public key --- crypto/src/crypto/agreement/DHAgreement.cs | 6 +++++- crypto/src/crypto/agreement/DHBasicAgreement.cs | 8 +++++++- crypto/src/crypto/parameters/DHPublicKeyParameters.cs | 2 +- 3 files changed, 13 insertions(+), 3 deletions(-) (limited to 'crypto/src') diff --git a/crypto/src/crypto/agreement/DHAgreement.cs b/crypto/src/crypto/agreement/DHAgreement.cs index b5af104f9..e988c0d53 100644 --- a/crypto/src/crypto/agreement/DHAgreement.cs +++ b/crypto/src/crypto/agreement/DHAgreement.cs @@ -85,7 +85,11 @@ namespace Org.BouncyCastle.Crypto.Agreement BigInteger p = dhParams.P; - BigInteger result = pub.Y.ModPow(privateValue, p); + BigInteger peerY = pub.Y; + if (peerY == null || peerY.CompareTo(BigInteger.One) <= 0 || peerY.CompareTo(p.Subtract(BigInteger.One)) >= 0) + throw new ArgumentException("Diffie-Hellman public key is weak"); + + BigInteger result = peerY.ModPow(privateValue, p); if (result.Equals(BigInteger.One)) throw new InvalidOperationException("Shared key can't be 1"); diff --git a/crypto/src/crypto/agreement/DHBasicAgreement.cs b/crypto/src/crypto/agreement/DHBasicAgreement.cs index d6f017e32..6c3fe6595 100644 --- a/crypto/src/crypto/agreement/DHBasicAgreement.cs +++ b/crypto/src/crypto/agreement/DHBasicAgreement.cs @@ -56,7 +56,13 @@ namespace Org.BouncyCastle.Crypto.Agreement if (!pub.Parameters.Equals(dhParams)) throw new ArgumentException("Diffie-Hellman public key has wrong parameters."); - BigInteger result = pub.Y.ModPow(key.X, dhParams.P); + BigInteger p = dhParams.P; + + BigInteger peerY = pub.Y; + if (peerY == null || peerY.CompareTo(BigInteger.One) <= 0 || peerY.CompareTo(p.Subtract(BigInteger.One)) >= 0) + throw new ArgumentException("Diffie-Hellman public key is weak"); + + BigInteger result = peerY.ModPow(key.X, p); if (result.Equals(BigInteger.One)) throw new InvalidOperationException("Shared key can't be 1"); diff --git a/crypto/src/crypto/parameters/DHPublicKeyParameters.cs b/crypto/src/crypto/parameters/DHPublicKeyParameters.cs index 1704c47dc..e7aeeff19 100644 --- a/crypto/src/crypto/parameters/DHPublicKeyParameters.cs +++ b/crypto/src/crypto/parameters/DHPublicKeyParameters.cs @@ -46,7 +46,7 @@ namespace Org.BouncyCastle.Crypto.Parameters this.y = Validate(y, parameters); } - public BigInteger Y + public virtual BigInteger Y { get { return y; } } -- cgit 1.5.1