Java 类java.security.spec.ECPoint 实例源码

项目:mDL-ILP    文件:ECCUtils.java   
/**
 * Extract the raw bytes of the public ECC key in standard smart card format.
 * @param publicKey the key to extract the bytes of.
 * @param curveReference the reference to the standard curve of the key.
 * @return the extract bytes of the key.
 */
public static byte[] decodeECCPublicKeyX509(PublicKey publicKey, EllipticCurveParameters curveReference)
{
    byte[] publicKeyBytes = {};

    if (publicKey instanceof ECPublicKey)
    {
        final ECPoint w = ((ECPublicKey)publicKey).getW();

        final byte[] x = getStandardSizeInteger(w.getAffineX().toByteArray(), curveReference);
        final byte[] y = getStandardSizeInteger(w.getAffineY().toByteArray(), curveReference);

        publicKeyBytes = Bytes.concatenate(Bytes.bytes("04"), x, y); // Uncompressed format.
    }

    return publicKeyBytes;
}
项目:mDL-ILP    文件:EllipticCurveParameters.java   
public static ECParameterSpec encodeECParameterSpec(EllipticCurveParameters params) {

        // Field
        final BigInteger pInt = new BigInteger(1, params.getP());
        final ECField field = new ECFieldFp(pInt);

        final BigInteger aInt = new BigInteger(1, params.getA());
        final BigInteger bInt = new BigInteger(1, params.getB());
        final EllipticCurve curve = new EllipticCurve(field, aInt, bInt);

        // Fixed Point G
        final BigInteger xInt = new BigInteger(1, params.getX());
        final BigInteger yInt = new BigInteger(1, params.getY());
        final ECPoint g = new ECPoint(xInt, yInt);

        // Order N
        final BigInteger nInt = new BigInteger(1, params.getN());

        return new ECParameterSpec(curve, g, nInt, params.getH());
    }
项目:mDL-ILP    文件:ECCUtils.java   
/**
 * Extract the raw bytes of the public ECC key in standard smart card format.
 * @param publicKey the key to extract the bytes of.
 * @param curveReference the reference to the standard curve of the key.
 * @return the extract bytes of the key.
 */
public static byte[] decodeECCPublicKeyX509(PublicKey publicKey, EllipticCurveParameters curveReference)
{
    byte[] publicKeyBytes = {};

    if (publicKey instanceof ECPublicKey)
    {
        final ECPoint w = ((ECPublicKey)publicKey).getW();

        final byte[] x = getStandardSizeInteger(w.getAffineX().toByteArray(), curveReference);
        final byte[] y = getStandardSizeInteger(w.getAffineY().toByteArray(), curveReference);

        publicKeyBytes = Bytes.concatenate(Bytes.bytes("04"), x, y); // Uncompressed format.
    }

    return publicKeyBytes;
}
项目:mDL-ILP    文件:EllipticCurveParameters.java   
public static ECParameterSpec encodeECParameterSpec(EllipticCurveParameters params) {

        // Field
        final BigInteger pInt = new BigInteger(1, params.getP());
        final ECField field = new ECFieldFp(pInt);

        final BigInteger aInt = new BigInteger(1, params.getA());
        final BigInteger bInt = new BigInteger(1, params.getB());
        final EllipticCurve curve = new EllipticCurve(field, aInt, bInt);

        // Fixed Point G
        final BigInteger xInt = new BigInteger(1, params.getX());
        final BigInteger yInt = new BigInteger(1, params.getY());
        final ECPoint g = new ECPoint(xInt, yInt);

        // Order N
        final BigInteger nInt = new BigInteger(1, params.getN());

        return new ECParameterSpec(curve, g, nInt, params.getH());
    }
项目:ipack    文件:JCEECPublicKey.java   
public org.bouncycastle.math.ec.ECPoint getQ()
{
    if (ecSpec == null)
    {
        if (q instanceof org.bouncycastle.math.ec.ECPoint.Fp)
        {
            return new org.bouncycastle.math.ec.ECPoint.Fp(null, q.getX(), q.getY());
        }
        else
        {
            return new org.bouncycastle.math.ec.ECPoint.F2m(null, q.getX(), q.getY());
        }
    }

    return q;
}
项目:ipack    文件:BCDSTU4145PublicKey.java   
public org.bouncycastle.math.ec.ECPoint getQ()
{
    if (ecSpec == null)
    {
        if (q instanceof org.bouncycastle.math.ec.ECPoint.Fp)
        {
            return new org.bouncycastle.math.ec.ECPoint.Fp(null, q.getX(), q.getY());
        }
        else
        {
            return new org.bouncycastle.math.ec.ECPoint.F2m(null, q.getX(), q.getY());
        }
    }

    return q;
}
项目:ipack    文件:BCECPublicKey.java   
public org.bouncycastle.math.ec.ECPoint getQ()
{
    if (ecSpec == null)
    {
        if (q instanceof org.bouncycastle.math.ec.ECPoint.Fp)
        {
            return new org.bouncycastle.math.ec.ECPoint.Fp(null, q.getX(), q.getY());
        }
        else
        {
            return new org.bouncycastle.math.ec.ECPoint.F2m(null, q.getX(), q.getY());
        }
    }

    return q;
}
项目:ipack    文件:EC5Util.java   
public static ECParameterSpec convertSpec(
    EllipticCurve ellipticCurve,
    org.bouncycastle.jce.spec.ECParameterSpec spec)
{
    if (spec instanceof ECNamedCurveParameterSpec)
    {
        return new ECNamedCurveSpec(
            ((ECNamedCurveParameterSpec)spec).getName(),
            ellipticCurve,
            new ECPoint(
                spec.getG().getX().toBigInteger(),
                spec.getG().getY().toBigInteger()),
            spec.getN(),
            spec.getH());
    }
    else
    {
        return new ECParameterSpec(
            ellipticCurve,
            new ECPoint(
                spec.getG().getX().toBigInteger(),
                spec.getG().getY().toBigInteger()),
            spec.getN(),
            spec.getH().intValue());
    }
}
项目:ipack    文件:BCECGOST3410PublicKey.java   
public org.bouncycastle.math.ec.ECPoint getQ()
{
    if (ecSpec == null)
    {
        if (q instanceof org.bouncycastle.math.ec.ECPoint.Fp)
        {
            return new org.bouncycastle.math.ec.ECPoint.Fp(null, q.getX(), q.getY());
        }
        else
        {
            return new org.bouncycastle.math.ec.ECPoint.F2m(null, q.getX(), q.getY());
        }
    }

    return q;
}
项目:citizen-sdk-android    文件:CryptoService.java   
private static ECPublicKey importBrowserAuthPublicKey(String publicKey)
throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException
 {
     int xPos = publicKey.indexOf('x');
     int yPos = publicKey.indexOf('y');

     if (xPos != 0 || yPos < 0 || xPos >= yPos - 1 || publicKey.length() <= yPos + 2) {
        throw new InvalidKeyException("Incorrectly formatted ECDH key.");
     }

     String x = publicKey.substring(publicKey.indexOf('x') + 1, publicKey.indexOf('y'));
     String y = publicKey.substring(publicKey.indexOf('y') + 1);

     KeyFactory kf = KeyFactory.getInstance("EC");

     ECPoint point = new ECPoint(new BigInteger(x, 16), new BigInteger(y, 16));

     ECPublicKey convertedPubKey = (ECPublicKey) kf.generatePublic(new ECPublicKeySpec(point, BROWSER_AUTH_EC_SPEC));

     return convertedPubKey;
 }
项目:RISE-V2G    文件:SecurityUtils.java   
/**
 * Returns the ECPublicKey instance from its encoded raw bytes. 
 * The first byte has the fixed value 0x04 indicating the uncompressed form.
 * Therefore, the byte array must be of form: [0x04, x coord of point (32 bytes), y coord of point (32 bytes)]
 * 
 * @param publicKeyBytes The byte array representing the encoded raw bytes of the public key
 * @return The ECPublicKey instance
 */
public static ECPublicKey getPublicKey(byte[] publicKeyBytes) {
    // First we separate x and y of coordinates into separate variables
    byte[] x = new byte[32];
    byte[] y = new byte[32];
    System.arraycopy(publicKeyBytes, 1, x, 0, 32);
    System.arraycopy(publicKeyBytes, 33, y, 0, 32);

    try {
        KeyFactory kf = KeyFactory.getInstance("EC");

        AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
        parameters.init(new ECGenParameterSpec("secp256r1"));
        ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);

        ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)), ecParameterSpec);
        ECPublicKey ecPublicKey = (ECPublicKey) kf.generatePublic(ecPublicKeySpec);
        return ecPublicKey;
    } catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidKeySpecException e) {
        getLogger().error(e.getClass().getSimpleName() + " occurred when trying to get public key from raw bytes", e);
        return null;
    }
}
项目:openjdk-jdk10    文件:DOMKeyValue.java   
private static ECPoint decodePoint(byte[] data, EllipticCurve curve)
        throws IOException {
    if ((data.length == 0) || (data[0] != 4)) {
        throw new IOException("Only uncompressed point format " +
                              "supported");
    }
    // Per ANSI X9.62, an encoded point is a 1 byte type followed by
    // ceiling(log base 2 field-size / 8) bytes of x and the same of y.
    int n = (data.length - 1) / 2;
    if (n != ((curve.getField().getFieldSize() + 7) >> 3)) {
        throw new IOException("Point does not match field size");
    }

    byte[] xb = Arrays.copyOfRange(data, 1, 1 + n);
    byte[] yb = Arrays.copyOfRange(data, n + 1, n + 1 + n);

    return new ECPoint(new BigInteger(1, xb), new BigInteger(1, yb));
}
项目:mi-firma-android    文件:JseCryptoHelper.java   
private static Key loadEcPublicKey(final byte [] pubKey,
                                      final EcCurve curveName) throws NoSuchAlgorithmException,
                                                                      InvalidKeySpecException {
    final ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveName.toString());
    KeyFactory kf;
    try {
        kf = KeyFactory.getInstance(ECDH, BouncyCastleProvider.PROVIDER_NAME);
    }
    catch (final NoSuchProviderException e) {
        kf = KeyFactory.getInstance(ECDH);
    }
    final ECNamedCurveSpec params = new ECNamedCurveSpec(curveName.toString(), spec.getCurve(), spec.getG(), spec.getN());
    final ECPoint point =  ECPointUtil.decodePoint(params.getCurve(), pubKey);
    final java.security.spec.ECPublicKeySpec pubKeySpec = new java.security.spec.ECPublicKeySpec(point, params);
    return kf.generatePublic(pubKeySpec);
}
项目:mi-firma-android    文件:JseCryptoHelper.java   
private static ECParameterSpec mapNonceGMWithECDH(final BigInteger nonceS,
                                                  final ECPoint sharedSecretPointH,
                                                  final ECParameterSpec params) {
    // D~ = (p, a, b, G~, n, h) where G~ = [s]G + H
    final ECPoint generator = params.getGenerator();
    final EllipticCurve curve = params.getCurve();
    final BigInteger a = curve.getA();
    final BigInteger b = curve.getB();
    final ECFieldFp field = (ECFieldFp)curve.getField();
    final BigInteger p = field.getP();
    final BigInteger order = params.getOrder();
    final int cofactor = params.getCofactor();
    final ECPoint ephemeralGenerator = add(multiply(nonceS, generator, params), sharedSecretPointH, params);
    if (!toBouncyCastleECPoint(ephemeralGenerator, params).isValid()) {
        LOGGER.warning("Se ha generado un punto invalido"); //$NON-NLS-1$
    }
    return new ECParameterSpec(new EllipticCurve(new ECFieldFp(p), a, b), ephemeralGenerator, order, cofactor);
}
项目:mi-firma-android    文件:JseCryptoHelper.java   
private static Key loadEcPublicKey(final byte [] pubKey,
                                      final EcCurve curveName) throws NoSuchAlgorithmException,
                                                                      InvalidKeySpecException {
    final ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveName.toString());
    KeyFactory kf;
    try {
        kf = KeyFactory.getInstance(ECDH, BouncyCastleProvider.PROVIDER_NAME);
    }
    catch (final NoSuchProviderException e) {
        kf = KeyFactory.getInstance(ECDH);
    }
    final ECNamedCurveSpec params = new ECNamedCurveSpec(curveName.toString(), spec.getCurve(), spec.getG(), spec.getN());
    final ECPoint point =  ECPointUtil.decodePoint(params.getCurve(), pubKey);
    final java.security.spec.ECPublicKeySpec pubKeySpec = new java.security.spec.ECPublicKeySpec(point, params);
    return kf.generatePublic(pubKeySpec);
}
项目:mi-firma-android    文件:JseCryptoHelper.java   
private static ECParameterSpec mapNonceGMWithECDH(final BigInteger nonceS,
                                                  final ECPoint sharedSecretPointH,
                                                  final ECParameterSpec params) {
    // D~ = (p, a, b, G~, n, h) where G~ = [s]G + H
    final ECPoint generator = params.getGenerator();
    final EllipticCurve curve = params.getCurve();
    final BigInteger a = curve.getA();
    final BigInteger b = curve.getB();
    final ECFieldFp field = (ECFieldFp)curve.getField();
    final BigInteger p = field.getP();
    final BigInteger order = params.getOrder();
    final int cofactor = params.getCofactor();
    final ECPoint ephemeralGenerator = add(multiply(nonceS, generator, params), sharedSecretPointH, params);
    if (!toSpongyCastleECPoint(ephemeralGenerator, params).isValid()) {
        LOGGER.warning("Se ha generado un punto invalido"); //$NON-NLS-1$
    }
    return new ECParameterSpec(new EllipticCurve(new ECFieldFp(p), a, b), ephemeralGenerator, order, cofactor);
}
项目:bubichain-sdk-java    文件:Sm2keyCFCA.java   
public static ECParameterSpec CfcaCurve() {
    // 素数P
    BigInteger p = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16);

    // 基于素数P的有限域
    ECFieldFp gfp = new ECFieldFp(p);

    // 在有限域上的椭圆曲线y2 = x3 + ax + b
    EllipticCurve ellipticCurve = new EllipticCurve(gfp,
            new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16),
            new BigInteger("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16));

    // 基点G
    ECPoint G = new ECPoint(new BigInteger("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16),
            new BigInteger("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16));

    // G的阶
    BigInteger n = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16);

    // 设置基点
    ECParameterSpec ecParameterSpec = new ECParameterSpec(ellipticCurve, G, n, 1);
    return ecParameterSpec;
}
项目:bubichain-sdk-java    文件:Sm2keyCFCA.java   
public static ECParameterSpec CfcaCurve() {
    // 素数P
    BigInteger p = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16);

    // 基于素数P的有限域
    ECFieldFp gfp = new ECFieldFp(p);

    // 在有限域上的椭圆曲线y2 = x3 + ax + b
    EllipticCurve ellipticCurve = new EllipticCurve(gfp,
            new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16),
            new BigInteger("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16));

    // 基点G
    ECPoint G = new ECPoint(new BigInteger("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16),
            new BigInteger("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16));

    // G的阶
    BigInteger n = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16);

    // 设置基点
    ECParameterSpec ecParameterSpec = new ECParameterSpec(ellipticCurve, G, n, 1);
    return ecParameterSpec;
}
项目:openjdk9    文件:DOMKeyValue.java   
private static ECPoint decodePoint(byte[] data, EllipticCurve curve)
        throws IOException {
    if ((data.length == 0) || (data[0] != 4)) {
        throw new IOException("Only uncompressed point format " +
                              "supported");
    }
    // Per ANSI X9.62, an encoded point is a 1 byte type followed by
    // ceiling(log base 2 field-size / 8) bytes of x and the same of y.
    int n = (data.length - 1) / 2;
    if (n != ((curve.getField().getFieldSize() + 7) >> 3)) {
        throw new IOException("Point does not match field size");
    }

    byte[] xb = Arrays.copyOfRange(data, 1, 1 + n);
    byte[] yb = Arrays.copyOfRange(data, n + 1, n + 1 + n);

    return new ECPoint(new BigInteger(1, xb), new BigInteger(1, yb));
}
项目:conscrypt    文件:OpenSSLECGroupContext.java   
ECParameterSpec getECParameterSpec() {
    final String curveName = NativeCrypto.EC_GROUP_get_curve_name(groupCtx);

    final byte[][] curveParams = NativeCrypto.EC_GROUP_get_curve(groupCtx);
    final BigInteger p = new BigInteger(curveParams[0]);
    final BigInteger a = new BigInteger(curveParams[1]);
    final BigInteger b = new BigInteger(curveParams[2]);

    final ECField field = new ECFieldFp(p);

    final EllipticCurve curve = new EllipticCurve(field, a, b);

    final OpenSSLECPointContext generatorCtx = new OpenSSLECPointContext(this,
            new NativeRef.EC_POINT(NativeCrypto.EC_GROUP_get_generator(groupCtx)));
    final ECPoint generator = generatorCtx.getECPoint();

    final BigInteger order = new BigInteger(NativeCrypto.EC_GROUP_get_order(groupCtx));
    final BigInteger cofactor = new BigInteger(NativeCrypto.EC_GROUP_get_cofactor(groupCtx));

    ECParameterSpec spec = new ECParameterSpec(curve, generator, order, cofactor.intValue());
    Platform.setCurveName(spec, curveName);
    return spec;
}
项目:web-push-java    文件:EllipticCurveKeyUtil.java   
/**
 * Converts the ECDH public key to bytes (has to be 65 bytes in length)
 * @param publicKey Public key for ECDH p256 curve
 * @return bytearray representation of key
 */
public byte[] publicKeyToBytes(final ECPublicKey publicKey) throws DecoderException {
  ECPoint point = publicKey.getW();
  String x = point.getAffineX().toString(16);
  String y = point.getAffineY().toString(16);

  /*
   *  Format is 04 followed by 32 bytes (64 hex) each for the X,Y coordinates
  */
  StringBuilder sb = new StringBuilder();
  sb.append("04");

  for (int i = 0; i < 64 - x.length(); i++) {
    sb.append(0);
  }
  sb.append(x);

  for (int i = 0; i < 64 - y.length(); i++) {
    sb.append(0);
  }
  sb.append(y);
  return decodeHex(sb.toString().toCharArray());
}
项目:xmlsec-gost    文件:DOMKeyValue.java   
private static ECPoint decodePoint(byte[] data, EllipticCurve curve)
        throws IOException {
    if (data.length == 0 || data[0] != 4) {
        throw new IOException("Only uncompressed point format " +
                              "supported");
    }
    // Per ANSI X9.62, an encoded point is a 1 byte type followed by
    // ceiling(log base 2 field-size / 8) bytes of x and the same of y.
    int n = (data.length - 1) / 2;
    if (n != (curve.getField().getFieldSize() + 7) >> 3) {
        throw new IOException("Point does not match field size");
    }

    byte[] xb = Arrays.copyOfRange(data, 1, 1 + n);
    byte[] yb = Arrays.copyOfRange(data, n + 1, n + 1 + n);

    return new ECPoint(new BigInteger(1, xb), new BigInteger(1, yb));
}
项目:wycheproof    文件:EcdhTest.java   
/**
 * Returns this key as ECPublicKeySpec or null if the key cannot be represented as
 * ECPublicKeySpec. The later happens for example if the order of cofactor are not positive.
 */
public ECPublicKeySpec getSpec() {
  try {
    ECFieldFp fp = new ECFieldFp(p);
    EllipticCurve curve = new EllipticCurve(fp, a, b);
    ECPoint g = new ECPoint(gx, gy);
    // ECParameterSpec requires that the cofactor h is specified.
    if (h == null) {
      return null;
    }
    ECParameterSpec params = new ECParameterSpec(curve, g, n, h);
    ECPoint pubPoint = new ECPoint(pubx, puby);
    ECPublicKeySpec pub = new ECPublicKeySpec(pubPoint, params);
    return pub;
  } catch (Exception ex) {
    System.out.println(comment + " throws " + ex.toString());
    return null;
  }
}
项目:wycheproof    文件:EcUtil.java   
public static ECParameterSpec getNistCurveSpec(
    String decimalP, String decimalN, String hexB, String hexGX, String hexGY) {
  final BigInteger p = new BigInteger(decimalP);
  final BigInteger n = new BigInteger(decimalN);
  final BigInteger three = new BigInteger("3");
  final BigInteger a = p.subtract(three);
  final BigInteger b = new BigInteger(hexB, 16);
  final BigInteger gx = new BigInteger(hexGX, 16);
  final BigInteger gy = new BigInteger(hexGY, 16);
  final int h = 1;
  ECFieldFp fp = new ECFieldFp(p);
  java.security.spec.EllipticCurve curveSpec = new java.security.spec.EllipticCurve(fp, a, b);
  ECPoint g = new ECPoint(gx, gy);
  ECParameterSpec ecSpec = new ECParameterSpec(curveSpec, g, n, h);
  return ecSpec;
}
项目:wycheproof    文件:EcUtil.java   
public static ECParameterSpec getBrainpoolP256r1Params() {
  BigInteger p =
      new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", 16);
  BigInteger a =
      new BigInteger("7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9", 16);
  BigInteger b =
      new BigInteger("26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6", 16);
  BigInteger x =
      new BigInteger("8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262", 16);
  BigInteger y =
      new BigInteger("547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997", 16);
  BigInteger n =
      new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", 16);
  final int h = 1;
  ECFieldFp fp = new ECFieldFp(p);
  EllipticCurve curve = new EllipticCurve(fp, a, b);
  ECPoint g = new ECPoint(x, y);
  return new ECParameterSpec(curve, g, n, h);
}
项目:wycheproof    文件:EcUtil.java   
/**
 * Checks that a point is on a given elliptic curve. This method implements the partial public key
 * validation routine from Section 5.6.2.6 of NIST SP 800-56A
 * http://csrc.nist.gov/publications/nistpubs/800-56A/SP800-56A_Revision1_Mar08-2007.pdf A partial
 * public key validation is sufficient for curves with cofactor 1. See Section B.3 of
 * http://www.nsa.gov/ia/_files/SuiteB_Implementer_G-113808.pdf The point validations above are
 * taken from recommendations for ECDH, because parameter checks in ECDH are much more important
 * than for the case of ECDSA. Performing this test for ECDSA keys is mainly a sanity check.
 *
 * @param point the point that needs verification
 * @param ec the elliptic curve. This must be a curve over a prime order field.
 * @throws GeneralSecurityException if the field is binary or if the point is not on the curve.
 */
public static void checkPointOnCurve(ECPoint point, EllipticCurve ec)
    throws GeneralSecurityException {
  BigInteger p = getModulus(ec);
  BigInteger x = point.getAffineX();
  BigInteger y = point.getAffineY();
  if (x == null || y == null) {
    throw new GeneralSecurityException("point is at infinity");
  }
  // Check 0 <= x < p and 0 <= y < p.
  if (x.signum() == -1 || x.compareTo(p) != -1) {
    throw new GeneralSecurityException("x is out of range");
  }
  if (y.signum() == -1 || y.compareTo(p) != -1) {
    throw new GeneralSecurityException("y is out of range");
  }
  // Check y^2 == x^3 + a x + b (mod p)
  BigInteger lhs = y.multiply(y).mod(p);
  BigInteger rhs = x.multiply(x).add(ec.getA()).multiply(x).add(ec.getB()).mod(p);
  if (!lhs.equals(rhs)) {
    throw new GeneralSecurityException("Point is not on curve");
  }
}
项目:wycheproof    文件:EcUtil.java   
/**
 * Decompress a point
 *
 * @param x The x-coordinate of the point
 * @param bit0 true if the least significant bit of y is set.
 * @param ecParams contains the curve of the point. This must be over a prime order field.
 */
public static ECPoint getPoint(BigInteger x, boolean bit0, ECParameterSpec ecParams)
    throws GeneralSecurityException {
  EllipticCurve ec = ecParams.getCurve();
  ECField field = ec.getField();
  if (!(field instanceof ECFieldFp)) {
    throw new GeneralSecurityException("Only curves over prime order fields are supported");
  }
  BigInteger p = ((java.security.spec.ECFieldFp) field).getP();
  if (x.compareTo(BigInteger.ZERO) == -1 || x.compareTo(p) != -1) {
    throw new GeneralSecurityException("x is out of range");
  }
  // Compute rhs == x^3 + a x + b (mod p)
  BigInteger rhs = x.multiply(x).add(ec.getA()).multiply(x).add(ec.getB()).mod(p);
  BigInteger y = modSqrt(rhs, p);
  if (bit0 != y.testBit(0)) {
    y = p.subtract(y).mod(p);
  }
  return new ECPoint(x, y);
}
项目:wycheproof    文件:EcUtil.java   
/**
 * Returns a weak public key of order 3 such that the public key point is on the curve specified
 * in ecParams. This method is used to check ECC implementations for missing step in the
 * verification of the public key. E.g. implementations of ECDH must verify that the public key
 * contains a point on the curve as well as public and secret key are using the same curve.
 *
 * @param ecParams the parameters of the key to attack. This must be a curve in Weierstrass form
 *     over a prime order field.
 * @return a weak EC group with a genrator of order 3.
 */
public static ECPublicKeySpec getWeakPublicKey(ECParameterSpec ecParams)
    throws GeneralSecurityException {
  EllipticCurve curve = ecParams.getCurve();
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
  keyGen.initialize(ecParams);
  BigInteger p = getModulus(curve);
  BigInteger three = new BigInteger("3");
  while (true) {
    // Generate a point on the original curve
    KeyPair keyPair = keyGen.generateKeyPair();
    ECPublicKey pub = (ECPublicKey) keyPair.getPublic();
    ECPoint w = pub.getW();
    BigInteger x = w.getAffineX();
    BigInteger y = w.getAffineY();
    // Find the curve parameters a,b such that 3*w = infinity.
    // This is the case if the following equations are satisfied:
    //    3x == l^2 (mod p)
    //    l == (3x^2 + a) / 2*y (mod p)
    //    y^2 == x^3 + ax + b (mod p)
    BigInteger l;
    try {
      l = modSqrt(x.multiply(three), p);
    } catch (GeneralSecurityException ex) {
      continue;
    }
    BigInteger xSqr = x.multiply(x).mod(p);
    BigInteger a = l.multiply(y.add(y)).subtract(xSqr.multiply(three)).mod(p);
    BigInteger b = y.multiply(y).subtract(x.multiply(xSqr.add(a))).mod(p);
    EllipticCurve newCurve = new EllipticCurve(curve.getField(), a, b);
    // Just a sanity check.
    checkPointOnCurve(w, newCurve);
    // Cofactor and order are of course wrong.
    ECParameterSpec spec = new ECParameterSpec(newCurve, w, p, 1);
    return new ECPublicKeySpec(w, spec);
  }
}
项目:connectbot    文件:ECDSASHA2Verify.java   
/**
 * Encode EllipticCurvePoint to an OctetString
 */
public static byte[] encodeECPoint(ECPoint group, EllipticCurve curve)
{
    // M has len 2 ceil(log_2(q)/8) + 1 ?
    int elementSize = (curve.getField().getFieldSize() + 7) / 8;
    byte[] M = new byte[2 * elementSize + 1];

    // Uncompressed format
    M[0] = 0x04;

    {
        byte[] affineX = removeLeadingZeroes(group.getAffineX().toByteArray());
        System.arraycopy(affineX, 0, M, 1 + elementSize - affineX.length, affineX.length);
    }

    {
        byte[] affineY = removeLeadingZeroes(group.getAffineY().toByteArray());
        System.arraycopy(affineY, 0, M, 1 + elementSize + elementSize - affineY.length,
                         affineY.length);
    }

    return M;
}
项目:Aki-SSL    文件:EC5Util.java   
public static ECParameterSpec convertSpec(
    EllipticCurve ellipticCurve,
    org.bouncycastle.jce.spec.ECParameterSpec spec)
{
    if (spec instanceof ECNamedCurveParameterSpec)
    {
        return new ECNamedCurveSpec(
            ((ECNamedCurveParameterSpec)spec).getName(),
            ellipticCurve,
            new ECPoint(
                spec.getG().getAffineXCoord().toBigInteger(),
                spec.getG().getAffineYCoord().toBigInteger()),
            spec.getN(),
            spec.getH());
    }
    else
    {
        return new ECParameterSpec(
            ellipticCurve,
            new ECPoint(
                spec.getG().getAffineXCoord().toBigInteger(),
                spec.getG().getAffineYCoord().toBigInteger()),
            spec.getN(),
            spec.getH().intValue());
    }
}
项目:SI    文件:SecurityInfoSerDesTest.java   
@Test
public void security_info_rpk_ser_des_then_equal() throws Exception {
    byte[] publicX = Hex
            .decodeHex("89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5".toCharArray());
    byte[] publicY = Hex
            .decodeHex("cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68".toCharArray());
    // Get Elliptic Curve Parameter spec for secp256r1
    AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
    algoParameters.init(new ECGenParameterSpec("secp256r1"));
    ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

    // Create key specs
    KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)),
            parameterSpec);

    SecurityInfo si = SecurityInfo.newRawPublicKeyInfo("myendpoint",
            KeyFactory.getInstance("EC").generatePublic(publicKeySpec));

    byte[] data = SecurityInfoSerDes.serialize(si);

    assertEquals(
            "{\"ep\":\"myendpoint\",\"rpk\":{\"x\":\"89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5\",\"y\":\"cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68\",\"params\":\"secp256r1\"}}",
            new String(data));
    System.err.println(new String(SecurityInfoSerDes.serialize(SecurityInfoSerDes.deserialize(data))));
    assertEquals(si, SecurityInfoSerDes.deserialize(data));
}
项目:leshan    文件:SecurityInfoSerDesTest.java   
@Test
public void security_info_rpk_ser_des_then_equal() throws Exception {
    byte[] publicX = Hex
            .decodeHex("89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5".toCharArray());
    byte[] publicY = Hex
            .decodeHex("cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68".toCharArray());
    // Get Elliptic Curve Parameter spec for secp256r1
    AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
    algoParameters.init(new ECGenParameterSpec("secp256r1"));
    ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

    // Create key specs
    KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)),
            parameterSpec);

    SecurityInfo si = SecurityInfo.newRawPublicKeyInfo("myendpoint",
            KeyFactory.getInstance("EC").generatePublic(publicKeySpec));

    byte[] data = SecurityInfoSerDes.serialize(si);

    assertEquals(
            "{\"ep\":\"myendpoint\",\"rpk\":{\"x\":\"89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5\",\"y\":\"cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68\",\"params\":\"secp256r1\"}}",
            new String(data));
    System.err.println(new String(SecurityInfoSerDes.serialize(SecurityInfoSerDes.deserialize(data))));
    assertEquals(si, SecurityInfoSerDes.deserialize(data));
}
项目:animamea    文件:ECDSA5Test.java   
private void decodeTest()
{
    EllipticCurve curve = new EllipticCurve(
            new ECFieldFp(new BigInteger("6277101735386680763835789423207666416083908700390324961279")), // q
            new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
            new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b

    ECPoint p = ECPointUtil.decodePoint(curve, Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012"));

    if (!p.getAffineX().equals(new BigInteger("188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", 16)))
    {
        fail("x uncompressed incorrectly");
    }

    if (!p.getAffineY().equals(new BigInteger("7192b95ffc8da78631011ed6b24cdd573f977a11e794811", 16)))
    {
        fail("y uncompressed incorrectly");
    }
}
项目:UAF    文件:KeyCodec.java   
/**
 * Decode based on X, Y 32 byte integers
 * 
 * @param pubKey
 * @param curveName
 *            - Example secp256r1
 * @return
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
public static PublicKey getPubKeyFromCurve(byte[] pubKey, String curveName)
        throws InvalidKeySpecException, NoSuchAlgorithmException,
        NoSuchProviderException {

    ECNamedCurveParameterSpec spec = ECNamedCurveTable
            .getParameterSpec(curveName);
    KeyFactory kf = KeyFactory.getInstance("ECDSA",
            new BouncyCastleProvider());
    ECNamedCurveSpec params = new ECNamedCurveSpec(curveName,
            spec.getCurve(), spec.getG(), spec.getN());
    ECPoint point = ECPointUtil.decodePoint(params.getCurve(), pubKey);
    ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params);
    ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKeySpec);
    return pk;
}
项目:j2objc    文件:ECPointTest.java   
/**
 * Test #1 for <code>hashCode()</code> method.<br>
 *
 * Assertion: must return the same value if invoked
 * repeatedly on the same object.
 */
public final void testHashCode01() {
    ECPoint f = new ECPoint(BigInteger.valueOf(-23457L), BigInteger.ONE);
    int hc = f.hashCode();
    assertTrue(hc == f.hashCode() &&
               hc == f.hashCode() &&
               hc == f.hashCode() &&
               hc == f.hashCode() &&
               hc == f.hashCode() &&
               hc == f.hashCode() &&
               hc == f.hashCode() &&
               hc == f.hashCode());


    // the same for POINT_INFINITY
    hc = ECPoint.POINT_INFINITY.hashCode();
    assertTrue(hc == ECPoint.POINT_INFINITY.hashCode() &&
               hc == ECPoint.POINT_INFINITY.hashCode() &&
               hc == ECPoint.POINT_INFINITY.hashCode() &&
               hc == ECPoint.POINT_INFINITY.hashCode() &&
               hc == ECPoint.POINT_INFINITY.hashCode() &&
               hc == ECPoint.POINT_INFINITY.hashCode() &&
               hc == ECPoint.POINT_INFINITY.hashCode() &&
               hc == ECPoint.POINT_INFINITY.hashCode());
}
项目:SI    文件:SecurityInfoSerDesTest.java   
@Test
public void security_info_rpk_ser_des_then_equal() throws Exception {
    byte[] publicX = Hex
            .decodeHex("89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5".toCharArray());
    byte[] publicY = Hex
            .decodeHex("cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68".toCharArray());
    // Get Elliptic Curve Parameter spec for secp256r1
    AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
    algoParameters.init(new ECGenParameterSpec("secp256r1"));
    ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

    // Create key specs
    KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)),
            parameterSpec);

    SecurityInfo si = SecurityInfo.newRawPublicKeyInfo("myendpoint",
            KeyFactory.getInstance("EC").generatePublic(publicKeySpec));

    byte[] data = SecurityInfoSerDes.serialize(si);

    assertEquals(
            "{\"ep\":\"myendpoint\",\"rpk\":{\"x\":\"89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5\",\"y\":\"cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68\",\"params\":\"secp256r1\"}}",
            new String(data));
    System.err.println(new String(SecurityInfoSerDes.serialize(SecurityInfoSerDes.deserialize(data))));
    assertEquals(si, SecurityInfoSerDes.deserialize(data));
}
项目:j2ssh-maverick    文件:Ssh2EcdsaSha2NistPublicKey.java   
public static void main(String[] args) throws Exception {


    KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
    ECGenParameterSpec gps = new ECGenParameterSpec ("secp256r1"); // NIST P-256 
    kpg.initialize(gps); 
    KeyPair apair = kpg.generateKeyPair(); 
    ECPublicKey apub  = (ECPublicKey)apair.getPublic();
    ECParameterSpec aspec = apub.getParams();
    // could serialize aspec for later use (in compatible JRE)
    //
    // for test only reuse bogus pubkey, for real substitute values 
    ECPoint apoint = apub.getW();
    BigInteger x = apoint.getAffineX(), y = apoint.getAffineY();
    // construct point plus params to pubkey
    ECPoint bpoint = new ECPoint (x,y); 
    ECPublicKeySpec bpubs = new ECPublicKeySpec (bpoint, aspec);
    KeyFactory kfa = KeyFactory.getInstance ("EC");
    ECPublicKey bpub = (ECPublicKey) kfa.generatePublic(bpubs);

    new Ssh2EcdsaSha2NistPublicKey(bpub);
}
项目:tink    文件:EllipticCurves.java   
/**
 * Checks that a point is on a given elliptic curve.
 *
 * <p><b>Warning:</b> Please use {@link #validatePublicKey} if you want to validate a public key
 * to avoid invalid curve attacks or small subgroup attacks in ECDH.
 *
 * <p>This method implements the partial public key validation routine from Section 5.6.2.6 of <a
 * href="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf">NIST SP
 * 800-56A</a>. A partial public key validation is sufficient for curves with cofactor 1. See
 * Section B.3 of http://www.nsa.gov/ia/_files/SuiteB_Implementer_G-113808.pdf.
 *
 * <p>The point validations above are taken from recommendations for ECDH, because parameter
 * checks in ECDH are much more important than for the case of ECDSA. Performing this test for
 * ECDSA keys is mainly a sanity check.
 *
 * @param point the point that needs verification
 * @param ec the elliptic curve. This must be a curve over a prime order field.
 * @throws GeneralSecurityException if the field is binary or if the point is not on the curve.
 */
static void checkPointOnCurve(ECPoint point, EllipticCurve ec) throws GeneralSecurityException {
  BigInteger p = getModulus(ec);
  BigInteger x = point.getAffineX();
  BigInteger y = point.getAffineY();
  if (x == null || y == null) {
    throw new GeneralSecurityException("point is at infinity");
  }
  // Check 0 <= x < p and 0 <= y < p.
  if (x.signum() == -1 || x.compareTo(p) != -1) {
    throw new GeneralSecurityException("x is out of range");
  }
  if (y.signum() == -1 || y.compareTo(p) != -1) {
    throw new GeneralSecurityException("y is out of range");
  }
  // Check y^2 == x^3 + a x + b (mod p)
  BigInteger lhs = y.multiply(y).mod(p);
  BigInteger rhs = x.multiply(x).add(ec.getA()).multiply(x).add(ec.getB()).mod(p);
  if (!lhs.equals(rhs)) {
    throw new GeneralSecurityException("Point is not on curve");
  }
}
项目:cryptoppjava    文件:EcData.java   
private EcData(ECKey key, ECPoint q, BigInteger x) {
    ECParameterSpec params = key.getParams();
    EllipticCurve curve = params.getCurve();
    curveModulus = ((ECFieldFp) curve.getField()).getP().toByteArray();
    curveA = curve.getA().toByteArray();
    curveB = curve.getB().toByteArray();
    gX = params.getGenerator().getAffineX().toByteArray();
    gY = params.getGenerator().getAffineY().toByteArray();
    n = params.getOrder().toByteArray();
    if (q == null) {
        qX = null;
        qY = null;
    } else {
        qX = q.getAffineX().toByteArray();
        qY = q.getAffineY().toByteArray();
    }
    this.x = x == null ? null : x.toByteArray();
}
项目:CryptMeme    文件:BCECGOST3410PublicKey.java   
public org.bouncycastle.math.ec.ECPoint getQ()
{
    if (ecSpec == null)
    {
        if (q instanceof org.bouncycastle.math.ec.ECPoint.Fp)
        {
            return new org.bouncycastle.math.ec.ECPoint.Fp(null, q.getAffineXCoord(), q.getAffineYCoord());
        }
        else
        {
            return new org.bouncycastle.math.ec.ECPoint.F2m(null, q.getAffineXCoord(), q.getAffineYCoord());
        }
    }

    return q;
}