Skip to content

Commit

Permalink
introduce constant for recurring error message
Browse files Browse the repository at this point in the history
  • Loading branch information
overheadhunter committed Feb 8, 2022
1 parent 978af94 commit 7d7b0aa
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/main/java/org/cryptomator/cryptolib/common/ECKeyPair.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

public class ECKeyPair implements Destroyable {

private static final String INVALID_KEY_ERROR = "Invalid EC Key";

private final KeyPair keyPair;
private boolean destroyed;

Expand Down Expand Up @@ -46,28 +48,28 @@ public ECPublicKey getPublic() {
// validations taken from https://neilmadden.blog/2017/05/17/so-how-do-you-validate-nist-ecdh-public-keys/
private static KeyPair verify(KeyPair keyPair, ECParameterSpec curveParams) {
PublicKey pk = keyPair.getPublic();
Preconditions.checkArgument(pk instanceof ECPublicKey, "Not an EC key");
Preconditions.checkArgument(pk instanceof ECPublicKey, INVALID_KEY_ERROR);
Preconditions.checkArgument(curveParams.getCofactor() == 1, "Verifying points on curves with cofactor not supported"); // see "Step 4" in linked post
ECPublicKey publicKey = (ECPublicKey) pk;
EllipticCurve curve = curveParams.getCurve();

// Step 1: Verify public key is not point at infinity.
Preconditions.checkArgument(!ECPoint.POINT_INFINITY.equals(publicKey.getW()), "Invalid Key");
Preconditions.checkArgument(!ECPoint.POINT_INFINITY.equals(publicKey.getW()), INVALID_KEY_ERROR);

final BigInteger x = publicKey.getW().getAffineX();
final BigInteger y = publicKey.getW().getAffineY();
final BigInteger p = ((ECFieldFp) curve.getField()).getP();

// Step 2: Verify x and y are in range [0,p-1]
Preconditions.checkArgument(x.compareTo(BigInteger.ZERO) >= 0 && x.compareTo(p) < 0, "Invalid Key");
Preconditions.checkArgument(y.compareTo(BigInteger.ZERO) >= 0 && y.compareTo(p) < 0, "Invalid Key");
Preconditions.checkArgument(x.compareTo(BigInteger.ZERO) >= 0 && x.compareTo(p) < 0, INVALID_KEY_ERROR);
Preconditions.checkArgument(y.compareTo(BigInteger.ZERO) >= 0 && y.compareTo(p) < 0, INVALID_KEY_ERROR);

// Step 3: Verify that y^2 == x^3 + ax + b (mod p)
final BigInteger a = curve.getA();
final BigInteger b = curve.getB();
final BigInteger ySquared = y.modPow(BigInteger.valueOf(2), p);
final BigInteger xCubedPlusAXPlusB = x.modPow(BigInteger.valueOf(3), p).add(a.multiply(x)).add(b).mod(p);
Preconditions.checkArgument(ySquared.equals(xCubedPlusAXPlusB), "Invalid key");
Preconditions.checkArgument(ySquared.equals(xCubedPlusAXPlusB), INVALID_KEY_ERROR);

return keyPair;
}
Expand Down

0 comments on commit 7d7b0aa

Please sign in to comment.