java.security.spec.ECPoint Java Examples

The following examples show how to use java.security.spec.ECPoint. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecurityInfoSerDesTest.java    From SI with BSD 2-Clause "Simplified" License 7 votes vote down vote up
@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));
}
 
Example #2
Source File: SecurityUtils.java    From RISE-V2G with MIT License 7 votes vote down vote up
/**
 * 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;
	}
}
 
Example #3
Source File: TPMAuthenticator.java    From webauthn4j with Apache License 2.0 6 votes vote down vote up
private TPMTPublic createTPMTPublic(PublicKey credentialPublicKey) {
    TPMIAlgPublic type = null;
    TPMIAlgHash nameAlg = TPMIAlgHash.TPM_ALG_SHA256;
    TPMAObject objectAttributes = new TPMAObject(394354);
    byte[] authPolicy = Base64UrlUtil.decode("nf_L82w4OuaZ-5ho3G3LidcVOIS-KAOSLBJBWL-tIq4");
    TPMUPublicId unique = null;
    TPMUPublicParms parameters = null;
    if (credentialPublicKey instanceof ECPublicKey) {
        ECPublicKey ecPublicKey = (ECPublicKey) credentialPublicKey;
        EllipticCurve curve = ecPublicKey.getParams().getCurve();
        parameters = new TPMSECCParms(
                new byte[2],
                new byte[2],
                TPMEccCurve.create(curve),
                new byte[2]
        );
        type = TPMIAlgPublic.TPM_ALG_ECDSA;
        ECPoint ecPoint = ecPublicKey.getW();
        byte[] x = ecPoint.getAffineX().toByteArray();
        byte[] y = ecPoint.getAffineY().toByteArray();
        unique = new ECCUnique(x, y);
    }
    return new TPMTPublic(type, nameAlg, objectAttributes, authPolicy, parameters, unique);
}
 
Example #4
Source File: ECKeyPairGenerator.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private KeyPair generateKeyPairNative(SecureRandom random)
    throws Exception {

    ECParameterSpec ecParams = (ECParameterSpec) params;
    byte[] encodedParams = ECUtil.encodeECParameterSpec(null, ecParams);

    // seed is twice the key size (in bytes) plus 1
    byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2];
    random.nextBytes(seed);
    Object[] keyBytes = generateECKeyPair(keySize, encodedParams, seed);

    // The 'params' object supplied above is equivalent to the native
    // one so there is no need to fetch it.
    // keyBytes[0] is the encoding of the native private key
    BigInteger s = new BigInteger(1, (byte[]) keyBytes[0]);

    PrivateKey privateKey = new ECPrivateKeyImpl(s, ecParams);

    // keyBytes[1] is the encoding of the native public key
    byte[] pubKey = (byte[]) keyBytes[1];
    ECPoint w = ECUtil.decodePoint(pubKey, ecParams.getCurve());
    PublicKey publicKey = new ECPublicKeyImpl(w, ecParams);

    return new KeyPair(publicKey, privateKey);
}
 
Example #5
Source File: SecureBox.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static PublicKey decodePublicKey(byte[] keyBytes)
        throws NoSuchAlgorithmException, InvalidKeyException {
    BigInteger x =
            new BigInteger(
                    /*signum=*/ 1,
                    Arrays.copyOfRange(keyBytes, 1, 1 + EC_COORDINATE_LEN_BYTES));
    BigInteger y =
            new BigInteger(
                    /*signum=*/ 1,
                    Arrays.copyOfRange(
                            keyBytes, 1 + EC_COORDINATE_LEN_BYTES, EC_PUBLIC_KEY_LEN_BYTES));

    // Checks if the point is indeed on the P-256 curve for security considerations
    validateEcPoint(x, y);

    KeyFactory keyFactory = KeyFactory.getInstance(EC_ALG);
    try {
        return keyFactory.generatePublic(new ECPublicKeySpec(new ECPoint(x, y), EC_PARAM_SPEC));
    } catch (InvalidKeySpecException ex) {
        // This should never happen
        throw new RuntimeException(ex);
    }
}
 
Example #6
Source File: SecurityInfoSerDesTest.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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));
}
 
Example #7
Source File: ECKeyPairGenerator.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private KeyPair generateKeyPairNative(SecureRandom random)
    throws Exception {

    ECParameterSpec ecParams = (ECParameterSpec) params;
    byte[] encodedParams = ECUtil.encodeECParameterSpec(null, ecParams);

    // seed is twice the key size (in bytes) plus 1
    byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2];
    random.nextBytes(seed);
    Object[] keyBytes = generateECKeyPair(keySize, encodedParams, seed);

    // The 'params' object supplied above is equivalent to the native
    // one so there is no need to fetch it.
    // keyBytes[0] is the encoding of the native private key
    BigInteger s = new BigInteger(1, (byte[]) keyBytes[0]);

    PrivateKey privateKey = new ECPrivateKeyImpl(s, ecParams);

    // keyBytes[1] is the encoding of the native public key
    byte[] pubKey = (byte[]) keyBytes[1];
    ECPoint w = ECUtil.decodePoint(pubKey, ecParams.getCurve());
    PublicKey publicKey = new ECPublicKeyImpl(w, ecParams);

    return new KeyPair(publicKey, privateKey);
}
 
Example #8
Source File: EcdhTest.java    From wycheproof with Apache License 2.0 6 votes vote down vote up
@SlowTest(providers = 
    {ProviderType.BOUNCY_CASTLE, ProviderType.SPONGY_CASTLE, ProviderType.OPENJDK})
@Test
public void testTimingBrainpoolP256r1() throws Exception {
  // edge case for Jacobian and projective coordinates
  BigInteger x1 =
      new BigInteger("79838c22d2b8dc9af2e6cf56f8826dc3dfe10fcb17b6aaaf551ee52bef12f826", 16);
  BigInteger y1 =
      new BigInteger("1e2ed3d453088c8552c6feecf898667bc1e15905002edec6b269feb7bea09d5b", 16);
  ECPoint p1 = new ECPoint(x1, y1);

  // random point
  BigInteger x2 =
      new BigInteger("2720b2e821b2ac8209b573bca755a68821e1e09deb580666702570dd527dd4c1", 16);
  BigInteger y2 =
      new BigInteger("25cdd610243c7e693fad7bd69b43ae3e63e94317c4c6b717d9c8bc3be8c996fb", 16);
  ECPoint p2 = new ECPoint(x2, y2);
  testTiming(EcUtil.getBrainpoolP256r1Params(), p1, p2, new BigInteger("2"), 255,
             "brainpoolP256r1");
}
 
Example #9
Source File: EcUtil.java    From wycheproof with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #10
Source File: JWSServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private JWSVerifier from(ECKey ecKey) {
    try {
        Curve curve = Curve.parse(ecKey.getCrv());
        if(curve.getStdName()==null) {
            throw new IllegalArgumentException("Unknown EC Curve: "+ecKey.getCrv());
        }
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
        parameters.init(new ECGenParameterSpec(curve.getStdName()));
        ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);

        byte[] x = Base64.getUrlDecoder().decode(ecKey.getX());
        byte[] y = Base64.getUrlDecoder().decode(ecKey.getY());
        ECPoint ecPoint = new ECPoint(new BigInteger(1,x), new BigInteger(1,y));

        ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(ecPoint, ecParameters);
        ECPublicKey ecPublicKey = (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(ecPublicKeySpec);
        return new ECDSAVerifier(ecPublicKey);
    }
    catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidKeySpecException | JOSEException ex) {
        LOGGER.error("Unable to build Verifier from Elliptic Curve (EC) key",ex);
        throw new IllegalArgumentException("Signature is using and unknown/not managed key");
    }
}
 
Example #11
Source File: ECKeyTest.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
@Test
public void testToJsonWebKey() throws Exception {
	ECGenParameterSpec gps = new ECGenParameterSpec(EcKey.P521);
	EC_KEY_GENERATOR.initialize(gps);
	KeyPair keyPair = EC_KEY_GENERATOR.generateKeyPair();
	
	ECPublicKey apub = (ECPublicKey) keyPair.getPublic();
	ECPoint point = apub.getW();
	ECPrivateKey apriv = (ECPrivateKey) keyPair.getPrivate();
	
	JsonWebKey jwk = new JsonWebKey()
			.withKid("kid")
			.withCrv(JsonWebKeyCurveName.P_521)
			.withX(point.getAffineX().toByteArray())
			.withY(point.getAffineY().toByteArray())
			.withD(apriv.getS().toByteArray())
			.withKty(JsonWebKeyType.EC);
	
	EcKey newKey = new EcKey("kid", keyPair);
	
	JsonWebKey newJwk = newKey.toJsonWebKey();
	//set missing parameters
	newJwk.withKid("kid");
	
	assertEquals(jwk, newJwk);	
}
 
Example #12
Source File: Ssh2EcdsaSha2NistPublicKey.java    From j2ssh-maverick with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #13
Source File: KeyCodec.java    From UAF with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #14
Source File: EC5Util.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public static ECParameterSpec convertSpec(
    EllipticCurve ellipticCurve,
    org.ripple.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());
    }
}
 
Example #15
Source File: ECDHKeyExchange.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
void checkConstraints(AlgorithmConstraints constraints,
        byte[] encodedPoint) throws SSLHandshakeException {
    try {

        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                ECUtil.decodePoint(encodedPoint, params.getCurve());
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);

        KeyFactory kf = KeyFactory.getInstance("EC");
        ECPublicKey pubKey = (ECPublicKey)kf.generatePublic(spec);

        // check constraints of ECPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), pubKey)) {
            throw new SSLHandshakeException(
                "ECPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate ECPublicKey").initCause(e);
    }
}
 
Example #16
Source File: DOMKeyValue.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
void getMethods() throws ClassNotFoundException, NoSuchMethodException {
    Class c  = Class.forName("sun.security.ec.ECParameters");
    Class[] params = new Class[] { ECPoint.class, EllipticCurve.class };
    encodePoint = c.getMethod("encodePoint", params);
    params = new Class[] { ECParameterSpec.class };
    getCurveName = c.getMethod("getCurveName", params);
    params = new Class[] { byte[].class, EllipticCurve.class };
    decodePoint = c.getMethod("decodePoint", params);
    c  = Class.forName("sun.security.ec.NamedCurve");
    params = new Class[] { String.class };
    getECParameterSpec = c.getMethod("getECParameterSpec", params);
}
 
Example #17
Source File: ECNamedCurveSpec.java    From ripple-lib-java with ISC License 5 votes vote down vote up
public ECNamedCurveSpec(
    String                              name,
    ECCurve                             curve,
    org.ripple.bouncycastle.math.ec.ECPoint    g,
    BigInteger                          n,
    BigInteger                          h,
    byte[]                              seed)
{
    super(convertCurve(curve, seed), convertPoint(g), n, h.intValue());
    
    this.name = name;
}
 
Example #18
Source File: KeyUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static byte[] getUncompressedEncodedECPoint(ECPoint point, int orderBitLength) {
  int orderByteLength = (orderBitLength + 7) / 8;
  byte[] keyData = new byte[1 + orderByteLength * 2];
  keyData[0] = 4;
  unsignedByteArrayCopy(keyData, 1, orderByteLength, point.getAffineX());
  unsignedByteArrayCopy(keyData, 1 + orderByteLength, orderByteLength, point.getAffineY());
  return keyData;
}
 
Example #19
Source File: JsonWebSignatureTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
private PublicKey buildEs256PublicKey(String x, String y)
    throws NoSuchAlgorithmException, InvalidParameterSpecException, InvalidKeySpecException {
  AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
  parameters.init(new ECGenParameterSpec("secp256r1"));
  ECPublicKeySpec ecPublicKeySpec =
      new ECPublicKeySpec(
          new ECPoint(
              new BigInteger(1, Base64.decodeBase64(x)),
              new BigInteger(1, Base64.decodeBase64(y))),
          parameters.getParameterSpec(ECParameterSpec.class));
  KeyFactory keyFactory = KeyFactory.getInstance("EC");
  return keyFactory.generatePublic(ecPublicKeySpec);
}
 
Example #20
Source File: ECKeyPairGenerator.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Override
public KeyPair generateKeyPair() {

    byte[] encodedParams =
        ECUtil.encodeECParameterSpec(null, (ECParameterSpec)params);

    // seed is twice the key size (in bytes) plus 1
    byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2];
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    random.nextBytes(seed);

    try {

        long[] handles = generateECKeyPair(keySize, encodedParams, seed);

        // The 'params' object supplied above is equivalent to the native
        // one so there is no need to fetch it.

        // handles[0] points to the native private key
        BigInteger s = new BigInteger(1, getEncodedBytes(handles[0]));

        PrivateKey privateKey =
            new ECPrivateKeyImpl(s, (ECParameterSpec)params);

        // handles[1] points to the native public key
        ECPoint w = ECUtil.decodePoint(getEncodedBytes(handles[1]),
            ((ECParameterSpec)params).getCurve());
        PublicKey publicKey =
            new ECPublicKeyImpl(w, (ECParameterSpec)params);

        return new KeyPair(publicKey, privateKey);

    } catch (Exception e) {
        throw new ProviderException(e);
    }
}
 
Example #21
Source File: JCEECPrivateKey.java    From ripple-lib-java with ISC License 5 votes vote down vote up
public JCEECPrivateKey(
    String                  algorithm,
    ECPrivateKeyParameters  params,
    JCEECPublicKey          pubKey,
    ECParameterSpec         spec)
{
    ECDomainParameters      dp = params.getParameters();

    this.algorithm = algorithm;
    this.d = params.getD();

    if (spec == null)
    {
        EllipticCurve ellipticCurve = EC5Util.convertCurve(dp.getCurve(), dp.getSeed());

        this.ecSpec = new ECParameterSpec(
                        ellipticCurve,
                        new ECPoint(
                                dp.getG().getAffineXCoord().toBigInteger(),
                                dp.getG().getAffineYCoord().toBigInteger()),
                        dp.getN(),
                        dp.getH().intValue());
    }
    else
    {
        this.ecSpec = spec;
    }

    publicKey = getPublicKeyDetails(pubKey);
}
 
Example #22
Source File: BCDSTU4145PrivateKey.java    From ripple-lib-java with ISC License 5 votes vote down vote up
public BCDSTU4145PrivateKey(
    String algorithm,
    ECPrivateKeyParameters params,
    BCDSTU4145PublicKey pubKey,
    ECParameterSpec spec)
{
    ECDomainParameters dp = params.getParameters();

    this.algorithm = algorithm;
    this.d = params.getD();

    if (spec == null)
    {
        EllipticCurve ellipticCurve = EC5Util.convertCurve(dp.getCurve(), dp.getSeed());

        this.ecSpec = new ECParameterSpec(
            ellipticCurve,
            new ECPoint(
                dp.getG().getAffineXCoord().toBigInteger(),
                dp.getG().getAffineYCoord().toBigInteger()),
            dp.getN(),
            dp.getH().intValue());
    }
    else
    {
        this.ecSpec = spec;
    }

    publicKey = getPublicKeyDetails(pubKey);
}
 
Example #23
Source File: ECPointUtil.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * Decode a point on this curve which has been encoded using point
 * compression (X9.62 s 4.2.1 and 4.2.2) or regular encoding.
 * 
 * @param curve
 *            The elliptic curve.
 * @param encoded
 *            The encoded point.
 * @return the decoded point.
 */
public static ECPoint decodePoint(
   EllipticCurve curve, 
   byte[] encoded)
{
    ECCurve c = null;
    
    if (curve.getField() instanceof ECFieldFp)
    {
        c = new ECCurve.Fp(
                ((ECFieldFp)curve.getField()).getP(), curve.getA(), curve.getB());
    }
    else
    {
        int k[] = ((ECFieldF2m)curve.getField()).getMidTermsOfReductionPolynomial();
        
        if (k.length == 3)
        {
            c = new ECCurve.F2m(
                    ((ECFieldF2m)curve.getField()).getM(), k[2], k[1], k[0], curve.getA(), curve.getB());
        }
        else
        {
            c = new ECCurve.F2m(
                    ((ECFieldF2m)curve.getField()).getM(), k[0], curve.getA(), curve.getB());
        }
    }
    
    org.ripple.bouncycastle.math.ec.ECPoint p = c.decodePoint(encoded);

    return new ECPoint(p.getAffineXCoord().toBigInteger(), p.getAffineYCoord().toBigInteger());
}
 
Example #24
Source File: DOMKeyValue.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
EC(PublicKey key) throws KeyException {
    super(key);
    ECPublicKey ecKey = (ECPublicKey)key;
    ECPoint ecPoint = ecKey.getW();
    ecParams = ecKey.getParams();
    ecPublicKey = encodePoint(ecPoint, ecParams.getCurve());
}
 
Example #25
Source File: JWKParser.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private PublicKey createECPublicKey() {
    String crv = (String) jwk.getOtherClaims().get(ECPublicJWK.CRV);
    BigInteger x = new BigInteger(1, Base64Url.decode((String) jwk.getOtherClaims().get(ECPublicJWK.X)));
    BigInteger y = new BigInteger(1, Base64Url.decode((String) jwk.getOtherClaims().get(ECPublicJWK.Y)));

    String name;
    switch (crv) {
        case "P-256" :
            name = "secp256r1";
            break;
        case "P-384" :
            name = "secp384r1";
            break;
        case "P-521" :
            name = "secp521r1";
            break;
        default :
            throw new RuntimeException("Unsupported curve");
    }

    try {
        ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(name);
        ECNamedCurveSpec params = new ECNamedCurveSpec("prime256v1", spec.getCurve(), spec.getG(), spec.getN());
        ECPoint point = new ECPoint(x, y);
        ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params);

        KeyFactory kf = KeyFactory.getInstance("ECDSA");
        return kf.generatePublic(pubKeySpec);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #26
Source File: ECKeyPairGenerator.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public KeyPair generateKeyPair() {

    byte[] encodedParams =
        ECUtil.encodeECParameterSpec(null, (ECParameterSpec)params);

    // seed is twice the key size (in bytes) plus 1
    byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2];
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    random.nextBytes(seed);

    try {

        Object[] keyBytes = generateECKeyPair(keySize, encodedParams, seed);

        // The 'params' object supplied above is equivalent to the native
        // one so there is no need to fetch it.
        // keyBytes[0] is the encoding of the native private key
        BigInteger s = new BigInteger(1, (byte[])keyBytes[0]);

        PrivateKey privateKey =
            new ECPrivateKeyImpl(s, (ECParameterSpec)params);

        // keyBytes[1] is the encoding of the native public key
        ECPoint w = ECUtil.decodePoint((byte[])keyBytes[1],
            ((ECParameterSpec)params).getCurve());
        PublicKey publicKey =
            new ECPublicKeyImpl(w, (ECParameterSpec)params);

        return new KeyPair(publicKey, privateKey);

    } catch (Exception e) {
        throw new ProviderException(e);
    }
}
 
Example #27
Source File: BCDSTU4145PublicKey.java    From ripple-lib-java with ISC License 5 votes vote down vote up
public org.ripple.bouncycastle.math.ec.ECPoint getQ()
{
    if (ecSpec == null)
    {
        return q.getDetachedPoint();
    }

    return q;
}
 
Example #28
Source File: ECPrivateKeySpecTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
protected void setUp() throws Exception {
    super.setUp();

    ECPoint ecpoint = new ECPoint(BigInteger.valueOf(1), BigInteger
            .valueOf(1));
    EllipticCurve curve = new EllipticCurve(new ECFieldF2m(2), BigInteger
            .valueOf(1), BigInteger.valueOf(1));

    s = BigInteger.valueOf(1);
    ecparams = new ECParameterSpec(curve, ecpoint, BigInteger.valueOf(1), 1);
    ecpks = new ECPrivateKeySpec(s, ecparams);
}
 
Example #29
Source File: EciesEncryption.java    From protect with MIT License 5 votes vote down vote up
protected static byte[] encrypt(final byte[] message, final BigInteger r, final PublicKey publicKey) {
	if (publicKey instanceof ECPublicKey) {
		final ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
		final ECPoint javaPoint = ecPublicKey.getW();
		final EcPoint point = new EcPoint(javaPoint.getAffineX(), javaPoint.getAffineY());
		return encrypt(message, r, point);
	} else {
		throw new IllegalArgumentException("Key type must be ECPublicKey!");
	}
}
 
Example #30
Source File: DOMKeyValue.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
void getMethods() throws ClassNotFoundException, NoSuchMethodException {
    Class c  = Class.forName("sun.security.ec.ECParameters");
    Class[] params = new Class[] { ECPoint.class, EllipticCurve.class };
    encodePoint = c.getMethod("encodePoint", params);
    params = new Class[] { ECParameterSpec.class };
    getCurveName = c.getMethod("getCurveName", params);
    params = new Class[] { byte[].class, EllipticCurve.class };
    decodePoint = c.getMethod("decodePoint", params);
    c  = Class.forName("sun.security.ec.NamedCurve");
    params = new Class[] { String.class };
    getECParameterSpec = c.getMethod("getECParameterSpec", params);
}