Skip to content

Commit

Permalink
Restrict m value in F2m curves
Browse files Browse the repository at this point in the history
- configure limit w/ env. var. "Org.BouncyCastle.EC.F2m_MaxSize"
  • Loading branch information
peterdettman committed Apr 23, 2024
1 parent 346c124 commit 56daa6e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
18 changes: 11 additions & 7 deletions crypto/src/math/ec/ECCurve.cs
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,13 @@ public virtual ECPoint DecodePoint(ReadOnlySpan<byte> encoded)
}
#endif

internal static int ImplGetInteger(string envVariable, int defaultValue)
{
string property = Platform.GetEnvironmentVariable(envVariable);

return int.TryParse(property, out int value) ? value : defaultValue;
}

private class DefaultLookupTable
: AbstractECLookupTable
{
Expand Down Expand Up @@ -757,13 +764,6 @@ private static void ImplCheckQ(BigInteger q)
throw new ArgumentException("Fp q value not prime");
}

private static int ImplGetInteger(string envVariable, int defaultValue)
{
string property = Platform.GetEnvironmentVariable(envVariable);

return int.TryParse(property, out int value) ? value : defaultValue;
}

private static int ImplGetIterations(int bits, int certainty)
{
/*
Expand Down Expand Up @@ -966,6 +966,10 @@ public static BigInteger Inverse(int m, int[] ks, BigInteger x)

private static IFiniteField BuildField(int m, int k1, int k2, int k3)
{
int maxM = ImplGetInteger("Org.BouncyCastle.EC.F2m_MaxSize", 1142); // 2 * 571
if (m > maxM)
throw new ArgumentException("F2m m value out of range");

int[] exponents = (k2 | k3) == 0
? new int[]{ 0, k1, m }
: new int[]{ 0, k1, k2, k3, m };
Expand Down
20 changes: 20 additions & 0 deletions crypto/test/src/math/ec/test/ECPointTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,26 @@ private void ImplTestAdd(ECPoint[] p, ECPoint infinity)
}
}

[Test]
public void TestLargeMInF2m()
{
int m = 2048;
int k1 = 1;
BigInteger aTpb = new BigInteger("1000", 2);
BigInteger bTpb = new BigInteger("1001", 2);
BigInteger n = new BigInteger("23");
BigInteger h = new BigInteger("1");

try
{
F2mCurve curve = new F2mCurve(m, k1, aTpb, bTpb, n, h);
}
catch (ArgumentException e)
{
Assert.AreEqual("F2m m value out of range", e.Message);
}
}

/**
* Calls <code>implTestAdd()</code> for <code>Fp</code> and
* <code>F2m</code>.
Expand Down

0 comments on commit 56daa6e

Please sign in to comment.