Skip to content

Commit

Permalink
Add cofactor validation after point decompression
Browse files Browse the repository at this point in the history
  • Loading branch information
peterdettman committed Jul 25, 2014
1 parent 42e43cf commit e25e94a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
29 changes: 20 additions & 9 deletions core/src/main/java/org/bouncycastle/math/ec/ECCurve.java
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,12 @@ protected ECPoint decompressPoint(int yTilde, BigInteger X1)
y = y.negate();
}

return this.createRawPoint(x, y, true);
ECPoint p = this.createRawPoint(x, y, true);
if (!p.satisfiesCofactor())
{
throw new IllegalArgumentException("Invalid point");
}
return p;
}
}

Expand Down Expand Up @@ -974,14 +979,14 @@ synchronized BigInteger[] getSi()
*/
protected ECPoint decompressPoint(int yTilde, BigInteger X1)
{
ECFieldElement xp = fromBigInteger(X1), yp = null;
if (xp.isZero())
ECFieldElement x = fromBigInteger(X1), y = null;
if (x.isZero())
{
yp = b.sqrt();
y = b.sqrt();
}
else
{
ECFieldElement beta = xp.square().invert().multiply(b).add(a).add(xp);
ECFieldElement beta = x.square().invert().multiply(b).add(a).add(x);
ECFieldElement z = solveQuadraticEquation(beta);
if (z != null)
{
Expand All @@ -995,24 +1000,30 @@ protected ECPoint decompressPoint(int yTilde, BigInteger X1)
case COORD_LAMBDA_AFFINE:
case COORD_LAMBDA_PROJECTIVE:
{
yp = z.add(xp);
y = z.add(x);
break;
}
default:
{
yp = z.multiply(xp);
y = z.multiply(x);
break;
}
}
}
}

if (yp == null)
if (y == null)
{
throw new IllegalArgumentException("Invalid point compression");
}

return createRawPoint(xp, yp, true);
ECPoint p = this.createRawPoint(x, y, true);
if (!p.satisfiesCofactor())
{
throw new IllegalArgumentException("Invalid point");
}

return p;
}

/**
Expand Down
10 changes: 7 additions & 3 deletions core/src/main/java/org/bouncycastle/math/ec/ECPoint.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ protected ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElem
this.zs = zs;
}

protected boolean satisfiesCofactor()
{
BigInteger h = curve.getCofactor();
return h == null || h.equals(ECConstants.ONE) || !ECAlgorithms.referenceMultiply(this, h).isInfinity();
}

protected abstract boolean satisfiesCurveEquation();

public final ECPoint getDetachedPoint()
Expand Down Expand Up @@ -303,9 +309,7 @@ public boolean isValid()
return false;
}

BigInteger h = curve.getCofactor();
if (h != null && !h.equals(ECConstants.ONE)
&& ECAlgorithms.referenceMultiply(this, h).isInfinity())
if (!satisfiesCofactor())
{
return false;
}
Expand Down

0 comments on commit e25e94a

Please sign in to comment.