private static ECPoint doublePoint(ECPoint r, EllipticCurve curve) { if (r.equals(ECPoint.POINT_INFINITY)) return r; BigInteger slope = (r.getAffineX().pow(2)).multiply(THREE); slope = slope.add(curve.getA()); BigInteger prime = ((ECFieldFp) curve.getField()).getP(); // use NBI modInverse(); BigInteger tmp = r.getAffineY().multiply(TWO); tmp = new NativeBigInteger(tmp); slope = slope.multiply(tmp.modInverse(prime)); BigInteger xOut = slope.pow(2).subtract(r.getAffineX().multiply(TWO)).mod(prime); BigInteger yOut = (r.getAffineY().negate()).add(slope.multiply(r.getAffineX().subtract(xOut))).mod(prime); ECPoint out = new ECPoint(xOut, yOut); return out; }
private static ECPoint extractPublicKey(final ECPublicKey ecPublicKey) { final java.security.spec.ECPoint publicPointW = ecPublicKey.getW(); final BigInteger xCoord = publicPointW.getAffineX(); final BigInteger yCoord = publicPointW.getAffineY(); return CURVE.getCurve().createPoint(xCoord, yCoord); }
/** * SECG 2.3.3 ECPoint to Octet String */ public static byte[] getEncoded(ECPoint point, EllipticCurve curve) { int elementSize = getElementSize(curve); byte[] M = new byte[2 * elementSize + 1]; M[0] = 0x04; byte[] xBytes = stripLeadingZeroes(point.getAffineX().toByteArray()); byte[] yBytes = stripLeadingZeroes(point.getAffineY().toByteArray()); System.arraycopy(xBytes, 0, M, 1 + elementSize - xBytes.length, xBytes.length); System.arraycopy(yBytes, 0, M, 1 + 2 * elementSize - yBytes.length, yBytes.length); return M; }
static JsonObject getJwk(PublicKey publicKey, String algHeader) { if (publicKey instanceof RSAPublicKey) { RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; return Json.createObjectBuilder() .add(EXPONENT, base64UrlEncode(rsaPublicKey.getPublicExponent().toByteArray())) .add(KEY_TYPE, "RSA") .add(MODULUS, base64UrlEncode(modulusToByteArray(rsaPublicKey.getModulus()))) .build(); } else if (publicKey instanceof ECPublicKey) { ECPublicKey ecPublicKey = (ECPublicKey) publicKey; int fieldSize = ecPublicKey.getParams().getCurve().getField().getFieldSize(); return Json.createObjectBuilder() .add(CURVE, getCurveParameterFromAlgHeader(algHeader)) .add(KEY_TYPE, "EC") .add(X_COORDINATE, base64UrlEncode(coordinateToByteArray(fieldSize, ecPublicKey.getW().getAffineX()))) .add(Y_COORDINATE, base64UrlEncode(coordinateToByteArray(fieldSize, ecPublicKey.getW().getAffineY()))) .build(); } else { throw acme.unsupportedAcmeAccountPublicKeyType(publicKey.getAlgorithm()); } }
public boolean validate(byte[] r, byte[] s) throws Exception { BigInteger x = new BigInteger(1, r); BigInteger y = new BigInteger(1, s); ECPoint w = new ECPoint(x, y); if (w.equals(ECPoint.POINT_INFINITY)) { return false; } ECParameterSpec params = publicKey.getParams(); EllipticCurve curve = params.getCurve(); BigInteger p = ((ECFieldFp) curve.getField()).getP(); BigInteger p_sub1 = p.subtract(BigInteger.ONE); if (!(x.compareTo(p_sub1) <= 0 && y.compareTo(p_sub1) <= 0)) { return false; } BigInteger tmp = x.multiply(curve.getA()). add(curve.getB()). add(x.modPow(three, p)). mod(p); BigInteger y_2 = y.modPow(two, p); return y_2.equals(tmp); }
BigInteger p = new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"); ECFieldFp ecFieldFp = new ECFieldFp(p); BigInteger a = new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16); BigInteger b = new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16); EllipticCurve ellipticCurve = new EllipticCurve(ecFieldFp, a, b); BigInteger x = new BigInteger("110282003749548856476348533541186204577905061504881242240149511594420911"); BigInteger y = new BigInteger("869078407435509378747351873793058868500210384946040694651368759217025454"); ECPoint g = new ECPoint(x, y); BigInteger n = new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"); ECParameterSpec ecParameterSpec = new ECParameterSpec(ellipticCurve, g, n, 1);
if (ECPoint.POINT_INFINITY.equals(peerPublicKey.getW())) { throw new JweException(JweException.Error.KEY_ENCRYPTION_FAILURE); EllipticCurve curve = peerPublicKey.getParams().getCurve(); final BigInteger x = peerPublicKey.getW().getAffineX(); final BigInteger y = peerPublicKey.getW().getAffineY(); final BigInteger p = ((ECFieldFp) curve.getField()).getP(); if (x.compareTo(BigInteger.ZERO) < 0 || x.compareTo(p) >= 0 || y.compareTo(BigInteger.ZERO) < 0 || y.compareTo(p) >= 0) { throw new JweException(JweException.Error.KEY_ENCRYPTION_FAILURE); final BigInteger a = curve.getA(); final BigInteger b = curve.getB(); if (peerPublicKey.getParams().getCofactor() != 1) { throw new JweException(JweException.Error.KEY_ENCRYPTION_FAILURE);
public byte[] getSecret(byte[] r, byte[] s) throws Exception{ KeyFactory kf = KeyFactory.getInstance("EC"); ECPoint w = new ECPoint(new BigInteger(1, r), new BigInteger(1, s)); ECPublicKeySpec spec = new ECPublicKeySpec(w, publicKey.getParams()); PublicKey theirPublicKey = kf.generatePublic(spec); myKeyAgree.doPhase(theirPublicKey, true); return myKeyAgree.generateSecret(); }
protected void assertsEcdsaKey(ECPublicKey pubKey) { final String x = "48439561293906451759052585252797914202762949526041747995844080717082404635286"; final String y = "36134250956749795798585127919587881956611106672985015071877198253568414405109"; Assert.assertEquals(new BigInteger(x), pubKey.getParams().getGenerator().getAffineX()); Assert.assertEquals(new BigInteger(y), pubKey.getParams().getGenerator().getAffineY()); }
public static ECPoint decodePoint(byte[] encodedBytes, EllipticCurve elliptiCcurve) { if (encodedBytes[0] != 0x04) { throw new IllegalArgumentException("Only uncompressed format is supported"); } int size = (elliptiCcurve.getField().getFieldSize() + 7) / 8; byte affineXBytes[] = new byte[size]; byte affineYBytes[] = new byte[size]; System.arraycopy(encodedBytes, 1, affineXBytes, 0, size); System.arraycopy(encodedBytes, size + 1, affineYBytes, 0, size); return new ECPoint(new BigInteger(1, affineXBytes), new BigInteger(1, affineYBytes)); }
case SHA256WITHECDSA: case SM3WITHSM2: BigInteger d = new BigInteger(1, prikey); ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec((String) this.curveParams[0]); ECParameterSpec paramSpec = new ECNamedCurveSpec(spec.getName(), spec.getCurve(), spec.getG(), spec.getN()); this.privateKey = kf.generatePrivate(priSpec); org.bouncycastle.math.ec.ECPoint Q = spec.getG().multiply(d).normalize(); if (Q == null || Q.getAffineXCoord() == null || Q.getAffineYCoord() == null) { throw new SDKException(ErrorCode.OtherError("normalize error")); new ECPoint(Q.getAffineXCoord().toBigInteger(), Q.getAffineYCoord().toBigInteger()), paramSpec); this.publicKey = kf.generatePublic(pubSpec);
/** * SECG 2.3.4 Octet String to ECPoint */ public static ECPoint getDecoded(byte[] M, EllipticCurve curve) { int elementSize = getElementSize(curve); if (M.length != 2 * elementSize + 1 || M[0] != 0x04) { throw new SSHRuntimeException("Invalid 'f' for Elliptic Curve " + curve.toString()); } byte[] xBytes = new byte[elementSize]; byte[] yBytes = new byte[elementSize]; System.arraycopy(M, 1, xBytes, 0, elementSize); System.arraycopy(M, 1 + elementSize, yBytes, 0, elementSize); return new ECPoint(new BigInteger(1, xBytes), new BigInteger(1, yBytes)); }
/** Checks that the public key's params spec is the same as the private key's params spec. */ static void validatePublicKeySpec(ECPublicKey publicKey, ECPrivateKey privateKey) throws GeneralSecurityException { try { ECParameterSpec publicKeySpec = publicKey.getParams(); ECParameterSpec privateKeySpec = privateKey.getParams(); if (!publicKeySpec.getCurve().equals(privateKeySpec.getCurve()) || !publicKeySpec.getGenerator().equals(privateKeySpec.getGenerator()) || !publicKeySpec.getOrder().equals(privateKeySpec.getOrder()) || publicKeySpec.getCofactor() != privateKeySpec.getCofactor()) { throw new GeneralSecurityException("invalid public key spec"); } } catch (IllegalArgumentException | NullPointerException ex) { // The Java security providers on Android K and Android L might throw these unchecked // exceptions, converting them to a checked one to not crash the JVM. throw new GeneralSecurityException(ex.toString()); } }
private void checkPointIsOnCurve(ECPublicKey ephemeralPublicKey, ECPrivateKey privateKey) throws JoseException { // to prevent 'Invalid Curve Attack': for NIST curves, check whether public key is on the private key's curve. // from https://www.cs.bris.ac.uk/Research/CryptographySecurity/RWC/2017/nguyen.quan.pdf // there appear to be similar checks in the JVM starting with 1.8.0_51 but // doing it here explicitly seems prudent // (y^2) mod p = (x^3 + ax + b) mod p // thanks to Antonio Sanso for guidance on how to do this check ECParameterSpec ecParameterSpec = privateKey.getParams(); EllipticCurve curve = ecParameterSpec.getCurve(); ECPoint point = ephemeralPublicKey.getW(); BigInteger x = point.getAffineX(); BigInteger y = point.getAffineY(); BigInteger a = curve.getA(); BigInteger b = curve.getB(); BigInteger p = ((ECFieldFp) curve.getField()).getP(); BigInteger leftSide = (y.pow(2)).mod(p); BigInteger rightSide = (x.pow(3).add(a.multiply(x)).add(b)).mod(p); boolean onCurve = leftSide.equals(rightSide); if (!onCurve) { throw new JoseException(HeaderParameterNames.EPHEMERAL_PUBLIC_KEY + " is invalid for " + EllipticCurves.getName(curve)); } }
throw new XMLSecurityException("stax.unsupportedKeyValue"); final EllipticCurve curve = new EllipticCurve( new ECFieldFp( new BigInteger(ecCurveDefinition.getField(), 16) ), new BigInteger(ecCurveDefinition.getA(), 16), ECPoint ecPointG = ECDSAUtils.decodePoint(ecKeyValueType.getPublicKey(), curve); ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec( new ECPoint( ecPointG.getAffineX(), ecPointG.getAffineY() ), new ECParameterSpec( curve, new ECPoint( new BigInteger(ecCurveDefinition.getX(), 16), new BigInteger(ecCurveDefinition.getY(), 16)
private ECParameterSpec createSpec(EllipticCurve ellipticCurve, ECDomainParameters dp) { return new ECParameterSpec( ellipticCurve, new ECPoint( dp.getG().getAffineXCoord().toBigInteger(), dp.getG().getAffineYCoord().toBigInteger()), dp.getN(), dp.getH().intValue()); }
public static OpenSSLECGroupContext getInstance(ECParameterSpec params) throws InvalidAlgorithmParameterException { final String curveName = params.getCurveName(); if (curveName != null) { return OpenSSLECGroupContext.getCurveByName(curveName); } final EllipticCurve curve = params.getCurve(); final ECField field = curve.getField(); final int type; final BigInteger p; if (field instanceof ECFieldFp) { type = NativeCrypto.EC_CURVE_GFP; p = ((ECFieldFp) field).getP(); } else if (field instanceof ECFieldF2m) { type = NativeCrypto.EC_CURVE_GF2M; p = ((ECFieldF2m) field).getReductionPolynomial(); } else { throw new InvalidParameterException("unhandled field class " + field.getClass().getName()); } final ECPoint generator = params.getGenerator(); return OpenSSLECGroupContext.getInstance(type, p, curve.getA(), curve.getB(), generator.getAffineX(), generator.getAffineY(), params.getOrder(), BigInteger.valueOf(params.getCofactor())); }
long startTime = System.currentTimeMillis(); org.bouncycastle.jce.spec.ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(CURVE_NAME); ECField field = new ECFieldFp(ecSpec.getCurve().getField().getCharacteristic()); EllipticCurve curve = new EllipticCurve(field, ecSpec.getCurve().getA().toBigInteger(), ecSpec.getCurve().getB().toBigInteger()); ECPoint pointG = new ECPoint(ecSpec.getG().getXCoord().toBigInteger(), ecSpec.getG().getYCoord().toBigInteger()); ECParameterSpec spec = new ECParameterSpec(curve, pointG, ecSpec.getN(), ecSpec.getH().intValue()); KeyPairGenerator g = KeyPairGenerator.getInstance(KEY_PAIR_GENERATOR_TYPE); g.initialize(spec, new SecureRandom()); ECPublicKeySpec ecPublicSpec = new ECPublicKeySpec(((ECPublicKey) keysPair.getPublic()).getW(), spec); KeyFactory kf = KeyFactory.getInstance(KEY_FACTORY_TYPE); PrivateKey privateKey = kf.generatePrivate(ecPrivSpec); BigInteger serialNumber = BigInteger.valueOf(randomNumber >= 0 ? randomNumber : randomNumber * -1); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10));
ECPrivateKey ecPrivateKey = (ECPrivateKey)privateKey; System.out.println(ecPrivateKey.getS().toByteArray().length); ECPublicKey ecPublicKey = (ECPublicKey)publicKey; System.out.println(ecPublicKey.getW().getAffineX().toByteArray().length + ecPublicKey.getW().getAffineY().toByteArray().length);
public static byte[] encodePoint(ECPoint ecPoint, EllipticCurve ellipticCurve) { int size = (ellipticCurve.getField().getFieldSize() + 7) / 8; byte affineXBytes[] = stripLeadingZeros(ecPoint.getAffineX().toByteArray()); byte affineYBytes[] = stripLeadingZeros(ecPoint.getAffineY().toByteArray()); byte encodedBytes[] = new byte[size * 2 + 1]; encodedBytes[0] = 0x04; //uncompressed System.arraycopy(affineXBytes, 0, encodedBytes, size - affineXBytes.length + 1, affineXBytes.length); System.arraycopy(affineYBytes, 0, encodedBytes, encodedBytes.length - affineYBytes.length, affineYBytes.length); return encodedBytes; }