From ca2b4827e130211d6f5a8a743f1bbe99c332eca7 Mon Sep 17 00:00:00 2001 From: Peter Dettman Date: Mon, 24 Jun 2024 21:40:41 +0700 Subject: RSA: Use input range check from fips --- crypto/src/crypto/engines/RSACoreEngine.cs | 5 ++++- crypto/src/crypto/tls/TlsRsaKeyExchange.cs | 12 ++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/crypto/src/crypto/engines/RSACoreEngine.cs b/crypto/src/crypto/engines/RSACoreEngine.cs index dcc8d0101..a20b22b38 100644 --- a/crypto/src/crypto/engines/RSACoreEngine.cs +++ b/crypto/src/crypto/engines/RSACoreEngine.cs @@ -82,7 +82,10 @@ namespace Org.BouncyCastle.Crypto.Engines BigInteger input = new BigInteger(1, inBuf, inOff, inLen); - if (input.CompareTo(m_key.Modulus) >= 0) + if (input.CompareTo(BigInteger.One) <= 0) + throw new DataLengthException("input too small for RSA cipher."); + + if (input.CompareTo(m_key.Modulus.Subtract(BigInteger.One)) >= 0) throw new DataLengthException("input too large for RSA cipher."); return input; diff --git a/crypto/src/crypto/tls/TlsRsaKeyExchange.cs b/crypto/src/crypto/tls/TlsRsaKeyExchange.cs index 20c2360ea..7e38a529f 100644 --- a/crypto/src/crypto/tls/TlsRsaKeyExchange.cs +++ b/crypto/src/crypto/tls/TlsRsaKeyExchange.cs @@ -125,11 +125,15 @@ namespace Org.BouncyCastle.Crypto.Tls private static BigInteger ConvertInput(BigInteger modulus, byte[] buf, int off, int len) { - BigInteger result = BigIntegers.FromUnsignedByteArray(buf, off, len); - if (result.CompareTo(modulus) < 0) - return result; + BigInteger input = BigIntegers.FromUnsignedByteArray(buf, off, len); - throw new DataLengthException("input too large for RSA cipher."); + if (input.CompareTo(BigInteger.One) <= 0) + throw new DataLengthException("input too small for RSA cipher."); + + if (input.CompareTo(modulus.Subtract(BigInteger.One)) >= 0) + throw new DataLengthException("input too large for RSA cipher."); + + return input; } private static BigInteger Rsa(RsaKeyParameters privateKey, BigInteger input) -- cgit 1.4.1