java.security.spec.ECPublicKeySpec Java Examples

The following examples show how to use java.security.spec.ECPublicKeySpec. 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: 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 #4
Source File: OpenIdSigningKeyResolver.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
private static ECPublicKey generateECPublicKey(final JWK jwk) {
    final BigInteger x = decodeBase64(jwk.getX());
    final BigInteger y = decodeBase64(jwk.getY());

    try {
        final KeyFactory factory = KeyFactory.getInstance("EC");

        final ECPoint point = new ECPoint(x, y);
        final ECNamedCurveParameterSpec paramSpec = ECNamedCurveTable.getParameterSpec(jwk.getCurve());
        final ECNamedCurveSpec params = new ECNamedCurveSpec(jwk.getCurve(),
                                                             paramSpec.getCurve(),
                                                             paramSpec.getG(),
                                                             paramSpec.getN());

        final ECPublicKeySpec spec = new ECPublicKeySpec(point, params);

        return (ECPublicKey) factory.generatePublic(spec);
    } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
        Log.e(TAG, "failed to generate EC Public Key from JWK: " + jwk, e);

        return null;
    }
}
 
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: P12Manager.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public PublicKey getPublicKey()
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException,
                InvalidKeySpecException, NoSuchProviderException {
    ECPrivateKey privateKey = (ECPrivateKey) getPrivateKey();

    ECParameterSpec params = privateKey.getParams();

    org.bouncycastle.jce.spec.ECParameterSpec bcSpec =
            org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util.convertSpec(params, false);
    org.bouncycastle.math.ec.ECPoint q = bcSpec.getG().multiply(privateKey.getS());
    org.bouncycastle.math.ec.ECPoint bcW = bcSpec.getCurve().decodePoint(q.getEncoded(false));
    ECPoint w =
            new ECPoint(
                    bcW.getAffineXCoord().toBigInteger(), bcW.getAffineYCoord().toBigInteger());
    ECPublicKeySpec keySpec = new ECPublicKeySpec(w, tryFindNamedCurveSpec(params));
    return (PublicKey)
            KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME)
                    .generatePublic(keySpec);
}
 
Example #7
Source File: BCDSTU4145PublicKey.java    From ripple-lib-java with ISC License 6 votes vote down vote up
public BCDSTU4145PublicKey(
    org.ripple.bouncycastle.jce.spec.ECPublicKeySpec spec)
{
    this.q = spec.getQ();

    if (spec.getParams() != null) // can be null if implictlyCa
    {
        ECCurve curve = spec.getParams().getCurve();
        EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());

        this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
    }
    else
    {
        if (q.getCurve() == null)
        {
            org.ripple.bouncycastle.jce.spec.ECParameterSpec s = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();

            q = s.getCurve().createPoint(q.getAffineXCoord().toBigInteger(), q.getAffineYCoord().toBigInteger());
        }
        this.ecSpec = null;
    }
}
 
Example #8
Source File: ECDHClientKeyExchange.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
static void checkConstraints(AlgorithmConstraints constraints,
        ECPublicKey publicKey,
        byte[] encodedPoint) throws SSLHandshakeException {

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

        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKey peerPublicKey =
                (ECPublicKey)kf.generatePublic(spec);

        // check constraints of ECPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
                peerPublicKey)) {
            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 #9
Source File: ECDHKeyExchange.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
void checkConstraints(AlgorithmConstraints constraints,
        byte[] encodedPoint) throws SSLHandshakeException {
    try {

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

        KeyFactory kf = JsseJce.getKeyFactory("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 #10
Source File: ECDHKeyExchange.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
static ECDHECredentials valueOf(NamedGroup namedGroup,
    byte[] encodedPoint) throws IOException, GeneralSecurityException {

    if (namedGroup.type != NamedGroupType.NAMED_GROUP_ECDHE) {
        throw new RuntimeException(
            "Credentials decoding:  Not ECDHE named group");
    }

    if (encodedPoint == null || encodedPoint.length == 0) {
        return null;
    }

    ECParameterSpec parameters =
            JsseJce.getECParameterSpec(namedGroup.oid);
    if (parameters == null) {
        return null;
    }

    ECPoint point = JsseJce.decodePoint(
            encodedPoint, parameters.getCurve());
    KeyFactory factory = JsseJce.getKeyFactory("EC");
    ECPublicKey publicKey = (ECPublicKey)factory.generatePublic(
            new ECPublicKeySpec(point, parameters));
    return new ECDHECredentials(publicKey, namedGroup);
}
 
Example #11
Source File: BCECGOST3410PublicKey.java    From ripple-lib-java with ISC License 6 votes vote down vote up
public BCECGOST3410PublicKey(
    org.ripple.bouncycastle.jce.spec.ECPublicKeySpec spec)
{
    this.q = spec.getQ();

    if (spec.getParams() != null) // can be null if implictlyCa
    {
        ECCurve curve = spec.getParams().getCurve();
        EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());

        this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
    }
    else
    {
        if (q.getCurve() == null)
        {
            org.ripple.bouncycastle.jce.spec.ECParameterSpec s = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();

            q = s.getCurve().createPoint(q.getAffineXCoord().toBigInteger(), q.getAffineYCoord().toBigInteger());
        }
        this.ecSpec = null;
    }
}
 
Example #12
Source File: JCEECPublicKey.java    From ripple-lib-java with ISC License 6 votes vote down vote up
public JCEECPublicKey(
    String              algorithm,
    org.ripple.bouncycastle.jce.spec.ECPublicKeySpec     spec)
{
    this.algorithm = algorithm;
    this.q = spec.getQ();

    if (spec.getParams() != null) // can be null if implictlyCa
    {
        ECCurve curve = spec.getParams().getCurve();
        EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());

        this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
    }
    else
    {
        if (q.getCurve() == null)
        {
            org.ripple.bouncycastle.jce.spec.ECParameterSpec s = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();

            q = s.getCurve().createPoint(q.getAffineXCoord().toBigInteger(), q.getAffineYCoord().toBigInteger(), false);
        }               
        this.ecSpec = null;
    }
}
 
Example #13
Source File: PEMManager.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public PublicKey getPublicKey()
        throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
    ECPrivateKey privateKey = (ECPrivateKey) getPrivateKey();

    ECParameterSpec params = privateKey.getParams();

    org.bouncycastle.jce.spec.ECParameterSpec bcSpec =
            org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util.convertSpec(params, false);
    org.bouncycastle.math.ec.ECPoint q = bcSpec.getG().multiply(privateKey.getS());
    org.bouncycastle.math.ec.ECPoint bcW = bcSpec.getCurve().decodePoint(q.getEncoded(false));
    ECPoint w =
            new ECPoint(
                    bcW.getAffineXCoord().toBigInteger(), bcW.getAffineYCoord().toBigInteger());
    ECPublicKeySpec keySpec = new ECPublicKeySpec(w, tryFindNamedCurveSpec(params));
    return (PublicKey)
            KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME)
                    .generatePublic(keySpec);
}
 
Example #14
Source File: BCECGOST3410PublicKey.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public BCECGOST3410PublicKey(
    org.ripple.bouncycastle.jce.spec.ECPublicKeySpec spec)
{
    this.q = spec.getQ();

    if (spec.getParams() != null) // can be null if implictlyCa
    {
        ECCurve curve = spec.getParams().getCurve();
        EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());

        this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
    }
    else
    {
        if (q.getCurve() == null)
        {
            org.ripple.bouncycastle.jce.spec.ECParameterSpec s = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();

            q = s.getCurve().createPoint(q.getAffineXCoord().toBigInteger(), q.getAffineYCoord().toBigInteger());
        }
        this.ecSpec = null;
    }
}
 
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: TrailingSignatureAlgorithmTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
private void testSerialization(CryptoAlgorithm algorithm, String curveName, int[] x, int[] y, int[] expected) throws Exception {
    byte[] xBytes = TestUtils.unsignedBytesToSignedBytes(x);
    byte[] yBytes = TestUtils.unsignedBytesToSignedBytes(y);

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

    PublicKey publicKey = KeyFactory.getInstance("EC").generatePublic(
            new ECPublicKeySpec(new ECPoint(new BigInteger(1, xBytes), new BigInteger(1, yBytes)), ecParameterSpec));

    int[] result = TestUtils.signedBytesToUnsignedBytes(Utils.decodeBase64String(TrailingSignatureAlgorithm
            .forCryptoAlgorithm(algorithm)
            .serializePublicKey(publicKey)));

    assertArrayEquals(expected, result);
}
 
Example #17
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 #18
Source File: cryptoCommon.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 *
 * @param publickeybytes
 * @return
 * @throws java.security.spec.InvalidKeySpecException
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.NoSuchProviderException
 * @throws java.security.spec.InvalidParameterSpecException
 */
public static ECPublicKey getUserECPublicKey(byte[] publickeybytes) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, InvalidParameterSpecException {

    //append the sign byte to the arrays
    byte[] processedXData = new byte[EC_POINTSIZE];
    byte[] processedYData = new byte[EC_POINTSIZE];
    System.arraycopy(publickeybytes, 1, processedXData, 0, EC_POINTSIZE);
    System.arraycopy(publickeybytes, EC_POINTSIZE + 1, processedYData, 0, EC_POINTSIZE);

    ECPoint pubPoint = new ECPoint(new BigInteger(1, processedXData), new BigInteger(1, processedYData));
    AlgorithmParameters params = AlgorithmParameters.getInstance("EC", BC_FIPS_PROVIDER);
    params.init(new ECGenParameterSpec("prime256v1"));
    ECParameterSpec ecParameters = params.getParameterSpec(ECParameterSpec.class);
    ECPublicKeySpec pubECSpec = new ECPublicKeySpec(pubPoint, ecParameters);
    return (ECPublicKey) KeyFactory.getInstance("EC", BC_FIPS_PROVIDER).generatePublic(pubECSpec);
}
 
Example #19
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 #20
Source File: EcdhTest.java    From wycheproof with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
  }
}
 
Example #21
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 #22
Source File: JCEECPublicKey.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public JCEECPublicKey(
    String              algorithm,
    org.ripple.bouncycastle.jce.spec.ECPublicKeySpec     spec)
{
    this.algorithm = algorithm;
    this.q = spec.getQ();

    if (spec.getParams() != null) // can be null if implictlyCa
    {
        ECCurve curve = spec.getParams().getCurve();
        EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());

        this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
    }
    else
    {
        if (q.getCurve() == null)
        {
            org.ripple.bouncycastle.jce.spec.ECParameterSpec s = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();

            q = s.getCurve().createPoint(q.getAffineXCoord().toBigInteger(), q.getAffineYCoord().toBigInteger(), false);
        }               
        this.ecSpec = null;
    }
}
 
Example #23
Source File: BCDSTU4145PublicKey.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public BCDSTU4145PublicKey(
    org.ripple.bouncycastle.jce.spec.ECPublicKeySpec spec)
{
    this.q = spec.getQ();

    if (spec.getParams() != null) // can be null if implictlyCa
    {
        ECCurve curve = spec.getParams().getCurve();
        EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());

        this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
    }
    else
    {
        if (q.getCurve() == null)
        {
            org.ripple.bouncycastle.jce.spec.ECParameterSpec s = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();

            q = s.getCurve().createPoint(q.getAffineXCoord().toBigInteger(), q.getAffineYCoord().toBigInteger());
        }
        this.ecSpec = null;
    }
}
 
Example #24
Source File: ECDHKeyExchange.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
static ECDHECredentials valueOf(NamedGroup namedGroup,
    byte[] encodedPoint) throws IOException, GeneralSecurityException {

    if (namedGroup.spec != NamedGroupSpec.NAMED_GROUP_ECDHE) {
        throw new RuntimeException(
            "Credentials decoding:  Not ECDHE named group");
    }

    if (encodedPoint == null || encodedPoint.length == 0) {
        return null;
    }

    ECParameterSpec parameters =
            (ECParameterSpec)namedGroup.keAlgParamSpec;
    ECPoint point = ECUtil.decodePoint(
            encodedPoint, parameters.getCurve());
    KeyFactory factory = KeyFactory.getInstance("EC");
    ECPublicKey publicKey = (ECPublicKey)factory.generatePublic(
            new ECPublicKeySpec(point, parameters));
    return new ECDHECredentials(publicKey, namedGroup);
}
 
Example #25
Source File: BCECPublicKey.java    From ripple-lib-java with ISC License 5 votes vote down vote up
public BCECPublicKey(
    String algorithm,
    org.ripple.bouncycastle.jce.spec.ECPublicKeySpec spec,
    ProviderConfiguration configuration)
{
    this.algorithm = algorithm;
    this.q = spec.getQ();

    if (spec.getParams() != null) // can be null if implictlyCa
    {
        ECCurve curve = spec.getParams().getCurve();
        EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());

        // this may seem a little long-winded but it's how we pick up the custom curve.
        this.q = EC5Util.convertCurve(ellipticCurve).createPoint(spec.getQ().getAffineXCoord().toBigInteger(), spec.getQ().getAffineYCoord().toBigInteger());
        this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
    }
    else
    {
        if (q.getCurve() == null)
        {
            org.ripple.bouncycastle.jce.spec.ECParameterSpec s = configuration.getEcImplicitlyCa();

            q = s.getCurve().createPoint(q.getXCoord().toBigInteger(), q.getYCoord().toBigInteger(), false);
        }               
        this.ecSpec = null;
    }

    this.configuration = configuration;
}
 
Example #26
Source File: DNSSEC.java    From dnsjava with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static PublicKey toECDSAPublicKey(byte[] key, ECKeyInfo keyinfo)
    throws IOException, GeneralSecurityException {
  DNSInput in = new DNSInput(key);

  // RFC 6605 Section 4
  BigInteger x = readBigInteger(in, keyinfo.length);
  BigInteger y = readBigInteger(in, keyinfo.length);
  ECPoint q = new ECPoint(x, y);

  KeyFactory factory = KeyFactory.getInstance("EC");
  return factory.generatePublic(new ECPublicKeySpec(q, keyinfo.spec));
}
 
Example #27
Source File: BCECPublicKey.java    From ripple-lib-java with ISC License 5 votes vote down vote up
public BCECPublicKey(
    String algorithm,
    ECPublicKeySpec spec,
    ProviderConfiguration configuration)
{
    this.algorithm = algorithm;
    this.ecSpec = spec.getParams();
    this.q = EC5Util.convertPoint(ecSpec, spec.getW(), false);
    this.configuration = configuration;
}
 
Example #28
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 #29
Source File: Ssh2EcdsaSha2NistPublicKey.java    From j2ssh-maverick with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void init(byte[] blob, int start, int len) throws SshException {

		ByteArrayReader buf = new ByteArrayReader(blob, start, len);
		try {

			@SuppressWarnings("unused")
			String type = buf.readString();

			buf.readString();
			byte[] Q = buf.readBinaryString();

			ECParameterSpec ecspec = getCurveParams(curve);

			ECPoint p = ECUtils.fromByteArray(Q, ecspec.getCurve());
			KeyFactory keyFactory = JCEProvider
					.getProviderForAlgorithm(JCEAlgorithms.JCE_EC) == null ? KeyFactory
					.getInstance(JCEAlgorithms.JCE_EC) : KeyFactory
					.getInstance(JCEAlgorithms.JCE_EC, JCEProvider
							.getProviderForAlgorithm(JCEAlgorithms.JCE_EC));
			pub = (ECPublicKey) keyFactory.generatePublic(new ECPublicKeySpec(
					p, ecspec));
		} catch (Throwable t) {
			t.printStackTrace();
			throw new SshException("Failed to decode public key blob",
					SshException.INTERNAL_ERROR);
		} finally {
			try {
				buf.close();
			} catch (IOException e) {
			}
		}

	}
 
Example #30
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);
}