summaryrefslogtreecommitdiff
path: root/rsa.cpp
diff options
context:
space:
mode:
authorJeffrey Walton <noloader@gmail.com>2022-08-05 08:53:28 -0400
committerGitHub <noreply@github.com>2022-08-05 08:53:28 -0400
commit42bd192d8efa7b86ba649f6fc6730ecf32cedacf (patch)
treefc5bfb64e254f719481c8a03c283b143ec0726f7 /rsa.cpp
parent58dd9dc7c22ee270711ca552bbb25220d2359b43 (diff)
downloadcryptopp-git-42bd192d8efa7b86ba649f6fc6730ecf32cedacf.tar.gz
Ensure RSA m_u is not 0 for small moduli (GH #1136, PR #1137)
Diffstat (limited to 'rsa.cpp')
-rw-r--r--rsa.cpp31
1 files changed, 18 insertions, 13 deletions
diff --git a/rsa.cpp b/rsa.cpp
index 297c6dcb..27debbf4 100644
--- a/rsa.cpp
+++ b/rsa.cpp
@@ -126,19 +126,24 @@ void InvertibleRSAFunction::GenerateRandom(RandomNumberGenerator &rng, const Nam
if (m_e < 3 || m_e.IsEven())
throw InvalidArgument("InvertibleRSAFunction: invalid public exponent");
- RSAPrimeSelector selector(m_e);
- AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize)
- (Name::PointerToPrimeSelector(), selector.GetSelectorPointer());
- m_p.GenerateRandom(rng, primeParam);
- m_q.GenerateRandom(rng, primeParam);
-
- m_d = m_e.InverseMod(LCM(m_p-1, m_q-1));
- CRYPTOPP_ASSERT(m_d.IsPositive());
-
- m_dp = m_d % (m_p-1);
- m_dq = m_d % (m_q-1);
- m_n = m_p * m_q;
- m_u = m_q.InverseMod(m_p);
+ // Do this in a loop for small moduli. For small moduli, u' == 0 when p == q.
+ // https://github.com/weidai11/cryptopp/issues/1136
+ do
+ {
+ RSAPrimeSelector selector(m_e);
+ AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize)
+ (Name::PointerToPrimeSelector(), selector.GetSelectorPointer());
+ m_p.GenerateRandom(rng, primeParam);
+ m_q.GenerateRandom(rng, primeParam);
+
+ m_d = m_e.InverseMod(LCM(m_p-1, m_q-1));
+ CRYPTOPP_ASSERT(m_d.IsPositive());
+
+ m_dp = m_d % (m_p-1);
+ m_dq = m_d % (m_q-1);
+ m_n = m_p * m_q;
+ m_u = m_q.InverseMod(m_p);
+ } while (m_u.IsZero());
if (FIPS_140_2_ComplianceEnabled())
{