Java Code Examples for java.security.interfaces.ECPublicKey

The following examples show how to use java.security.interfaces.ECPublicKey. These examples are extracted from open source projects. 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 Project: fido2   Author: StrongKey   File: cryptoCommon.java    License: 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 #2
Source Project: java-jwt   Author: auth0   File: ECDSAAlgorithmTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldDecodeECDSA512JOSE() throws Exception {
    ECDSAAlgorithm algorithm512 = (ECDSAAlgorithm) Algorithm.ECDSA512((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC"));

    //Without padding
    byte[] joseSignature = createJOSESignature(66, false, false);
    byte[] derSignature = algorithm512.JOSEToDER(joseSignature);
    assertValidDERSignature(derSignature, 66, false, false);

    //With R padding
    joseSignature = createJOSESignature(66, true, false);
    derSignature = algorithm512.JOSEToDER(joseSignature);
    assertValidDERSignature(derSignature, 66, true, false);

    //With S padding
    joseSignature = createJOSESignature(66, false, true);
    derSignature = algorithm512.JOSEToDER(joseSignature);
    assertValidDERSignature(derSignature, 66, false, true);

    //With both paddings
    joseSignature = createJOSESignature(66, true, true);
    derSignature = algorithm512.JOSEToDER(joseSignature);
    assertValidDERSignature(derSignature, 66, true, true);
}
 
Example #3
Source Project: jdk8u_jdk   Author: JetBrains   File: CSignature.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void engineInitVerify(PublicKey key) throws InvalidKeyException {
    if (key == null) {
        throw new InvalidKeyException("Key cannot be null");
    }
    // This signature accepts only ECPublicKey
    if ((key instanceof ECPublicKey) == false) {
        throw new InvalidKeyException("Key type not supported: "
                + key.getClass());
    }

    if ((key instanceof CPublicKey) == false) {
        try {
            publicKey = importECPublicKey("EC",
                    CKey.generateECBlob(key),
                    KeyUtil.getKeySize(key));
        } catch (KeyStoreException e) {
            throw new InvalidKeyException(e);
        }
    } else {
        publicKey = (CPublicKey) key;
    }

    this.privateKey = null;
    resetDigest();
}
 
Example #4
Source Project: java-jwt   Author: auth0   File: ECDSABouncyCastleProviderTests.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldDecodeECDSA256DER() throws Exception {
    ECDSAAlgorithm algorithm256 = (ECDSAAlgorithm) Algorithm.ECDSA256((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC"));

    //Without padding
    byte[] derSignature = createDERSignature(32, false, false);
    byte[] joseSignature = algorithm256.DERToJOSE(derSignature);
    assertValidJOSESignature(joseSignature, 32, false, false);

    //With R padding
    derSignature = createDERSignature(32, true, false);
    joseSignature = algorithm256.DERToJOSE(derSignature);
    assertValidJOSESignature(joseSignature, 32, true, false);

    //With S padding
    derSignature = createDERSignature(32, false, true);
    joseSignature = algorithm256.DERToJOSE(derSignature);
    assertValidJOSESignature(joseSignature, 32, false, true);

    //With both paddings
    derSignature = createDERSignature(32, true, true);
    joseSignature = algorithm256.DERToJOSE(derSignature);
    assertValidJOSESignature(joseSignature, 32, true, true);
}
 
Example #5
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: P11ECDHKeyAgreement.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected Key engineDoPhase(Key key, boolean lastPhase)
        throws InvalidKeyException, IllegalStateException {
    if (privateKey == null) {
        throw new IllegalStateException("Not initialized");
    }
    if (publicValue != null) {
        throw new IllegalStateException("Phase already executed");
    }
    if (lastPhase == false) {
        throw new IllegalStateException
            ("Only two party agreement supported, lastPhase must be true");
    }
    if (key instanceof ECPublicKey == false) {
        throw new InvalidKeyException
            ("Key must be a PublicKey with algorithm EC");
    }
    ECPublicKey ecKey = (ECPublicKey)key;
    int keyLenBits = ecKey.getParams().getCurve().getField().getFieldSize();
    secretLen = (keyLenBits + 7) >> 3;
    publicValue = P11ECKeyFactory.getEncodedPublicValue(ecKey);
    return null;
}
 
Example #6
Source Project: azure-keyvault-java   Author: Azure   File: ECKeyTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testFromJsonWebKey() throws Exception {
    ECGenParameterSpec gps = new ECGenParameterSpec(EcKey.P384);
    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_384)
            .withX(point.getAffineX().toByteArray())
            .withY(point.getAffineY().toByteArray())
            .withD(apriv.getS().toByteArray())
            .withKty(JsonWebKeyType.EC);

    assertTrue(jwk.hasPrivateKey());
    
    EcKey newKey = EcKey.fromJsonWebKey(jwk, true);
    assertEquals("kid", newKey.getKid());
    doSignVerify(newKey, DIGEST_384);
}
 
Example #7
Source Project: java-jwt   Author: auth0   File: ECDSABouncyCastleProviderTests.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldDecodeECDSA384JOSE() throws Exception {
    ECDSAAlgorithm algorithm384 = (ECDSAAlgorithm) Algorithm.ECDSA384((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC"));

    //Without padding
    byte[] joseSignature = createJOSESignature(48, false, false);
    byte[] derSignature = algorithm384.JOSEToDER(joseSignature);
    assertValidDERSignature(derSignature, 48, false, false);

    //With R padding
    joseSignature = createJOSESignature(48, true, false);
    derSignature = algorithm384.JOSEToDER(joseSignature);
    assertValidDERSignature(derSignature, 48, true, false);

    //With S padding
    joseSignature = createJOSESignature(48, false, true);
    derSignature = algorithm384.JOSEToDER(joseSignature);
    assertValidDERSignature(derSignature, 48, false, true);

    //With both paddings
    joseSignature = createJOSESignature(48, true, true);
    derSignature = algorithm384.JOSEToDER(joseSignature);
    assertValidDERSignature(derSignature, 48, true, true);
}
 
Example #8
Source Project: jdk8u60   Author: chenghanpeng   File: ClientHandshaker.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void serverKeyExchange(ECDH_ServerKeyExchange mesg)
        throws IOException {
    if (debug != null && Debug.isOn("handshake")) {
        mesg.print(System.out);
    }
    ECPublicKey key = mesg.getPublicKey();
    ecdh = new ECDHCrypt(key.getParams(), sslContext.getSecureRandom());
    ephemeralServerKey = key;

    // check constraints of EC PublicKey
    if (!algorithmConstraints.permits(
        EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), ephemeralServerKey)) {

        throw new SSLHandshakeException("ECDH ServerKeyExchange " +
                "does not comply to algorithm constraints");
    }
}
 
Example #9
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: P11ECDHKeyAgreement.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected Key engineDoPhase(Key key, boolean lastPhase)
        throws InvalidKeyException, IllegalStateException {
    if (privateKey == null) {
        throw new IllegalStateException("Not initialized");
    }
    if (publicValue != null) {
        throw new IllegalStateException("Phase already executed");
    }
    if (lastPhase == false) {
        throw new IllegalStateException
            ("Only two party agreement supported, lastPhase must be true");
    }
    if (key instanceof ECPublicKey == false) {
        throw new InvalidKeyException
            ("Key must be a PublicKey with algorithm EC");
    }
    ECPublicKey ecKey = (ECPublicKey)key;
    int keyLenBits = ecKey.getParams().getCurve().getField().getFieldSize();
    secretLen = (keyLenBits + 7) >> 3;
    publicValue = P11ECKeyFactory.getEncodedPublicValue(ecKey);
    return null;
}
 
Example #10
Source Project: tron-wallet-android   Author: Dryec   File: ECKey.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generate a new keypair using the given Java Security Provider. <p> All private key operations
 * will use the provider.
 */
public ECKey(Provider provider, SecureRandom secureRandom) {
  this.provider = provider;

  final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance
      (provider, secureRandom);
  final KeyPair keyPair = keyPairGen.generateKeyPair();

  this.privKey = keyPair.getPrivate();

  final PublicKey pubKey = keyPair.getPublic();
  if (pubKey instanceof BCECPublicKey) {
    pub = ((BCECPublicKey) pubKey).getQ();
  } else if (pubKey instanceof ECPublicKey) {
    pub = extractPublicKey((ECPublicKey) pubKey);
  } else {
    throw new AssertionError(
        "Expected Provider " + provider.getName() +
            " to produce a subtype of ECPublicKey, found " +
            pubKey.getClass());
  }
}
 
Example #11
Source Project: azure-keyvault-java   Author: Azure   File: ECKeyTest.java    License: 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 Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: ClientHandshaker.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void serverKeyExchange(ECDH_ServerKeyExchange mesg)
        throws IOException {
    if (debug != null && Debug.isOn("handshake")) {
        mesg.print(System.out);
    }
    ECPublicKey key = mesg.getPublicKey();
    ecdh = new ECDHCrypt(key.getParams(), sslContext.getSecureRandom());
    ephemeralServerKey = key;

    // check constraints of EC PublicKey
    if (!algorithmConstraints.permits(
        EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), ephemeralServerKey)) {

        throw new SSLHandshakeException("ECDH ServerKeyExchange " +
                "does not comply to algorithm constraints");
    }
}
 
Example #13
Source Project: webauthn4j   Author: webauthn4j   File: TPMAuthenticator.java    License: 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 #14
Source Project: fusionauth-jwt   Author: FusionAuth   File: ECSignerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void round_trip_raw2() throws Exception {
  // Use a real public / private key in PEM format to sign a verify a message
  ECPublicKey publicKey = PEM.decode(new String(Files.readAllBytes(Paths.get("src/test/resources/ec_public_key_p_256.pem")))).getPublicKey();
  ECPrivateKey privateKey = PEM.decode(new String(Files.readAllBytes(Paths.get("src/test/resources/ec_private_key_p_256.pem")))).getPrivateKey();

  // Instance of signature class with SHA256withECDSA algorithm
  Signature signature = Signature.getInstance("SHA256withECDSA");
  signature.initSign(privateKey);

  // Sign a message
  String message = "text ecdsa with sha256";
  signature.update((message).getBytes(StandardCharsets.UTF_8));
  byte[] signatureBytes = signature.sign();

  // Validation
  Signature verifier = Signature.getInstance("SHA256withECDSA");
  verifier.initVerify(publicKey);
  verifier.update(message.getBytes(StandardCharsets.UTF_8));
  assertTrue(verifier.verify(signatureBytes));
}
 
Example #15
Source Project: j2ssh-maverick   Author: sshtools   File: Ssh2EcdsaSha2NistPublicKey.java    License: 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 #16
Source Project: UAF   Author: eBay   File: KeyCodec.java    License: 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 #17
Source Project: java-jwt   Author: auth0   File: ECDSAAlgorithmTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldThrowOnSignWhenThePrivateKeyIsInvalid() throws Exception {
    exception.expect(SignatureGenerationException.class);
    exception.expectMessage("The Token's Signature couldn't be generated when signing using the Algorithm: some-algorithm");
    exception.expectCause(isA(InvalidKeyException.class));

    CryptoHelper crypto = mock(CryptoHelper.class);
    when(crypto.createSignatureFor(anyString(), any(PrivateKey.class), any(byte[].class), any(byte[].class)))
            .thenThrow(InvalidKeyException.class);

    ECPublicKey publicKey = mock(ECPublicKey.class);
    ECPrivateKey privateKey = mock(ECPrivateKey.class);
    ECDSAKeyProvider provider = ECDSAAlgorithm.providerForKeys(publicKey, privateKey);
    Algorithm algorithm = new ECDSAAlgorithm(crypto, "some-alg", "some-algorithm", 32, provider);
    algorithm.sign(ES256HeaderBytes, new byte[0]);
}
 
Example #18
Source Project: termd   Author: alibaba   File: BaseTestSupport.java    License: Apache License 2.0 6 votes vote down vote up
public static <T extends Key> void assertKeyEquals(String message, T expected, T actual) {
    if (expected == actual) {
        return;
    }

    assertEquals(message + "[algorithm]", expected.getAlgorithm(), actual.getAlgorithm());

    if (expected instanceof RSAPublicKey) {
        assertRSAPublicKeyEquals(message, RSAPublicKey.class.cast(expected), RSAPublicKey.class.cast(actual));
    } else if (expected instanceof DSAPublicKey) {
        assertDSAPublicKeyEquals(message, DSAPublicKey.class.cast(expected), DSAPublicKey.class.cast(actual));
    } else if (expected instanceof ECPublicKey) {
        assertECPublicKeyEquals(message, ECPublicKey.class.cast(expected), ECPublicKey.class.cast(actual));
    } else if (expected instanceof RSAPrivateKey) {
        assertRSAPrivateKeyEquals(message, RSAPrivateKey.class.cast(expected), RSAPrivateKey.class.cast(actual));
    } else if (expected instanceof ECPrivateKey) {
        assertECPrivateKeyEquals(message, ECPrivateKey.class.cast(expected), ECPrivateKey.class.cast(actual));
    }
    assertArrayEquals(message + "[encdoded-data]", expected.getEncoded(), actual.getEncoded());
}
 
Example #19
Source Project: java-jwt   Author: auth0   File: ECDSABouncyCastleProviderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldThrowOnJOSESignatureConversionIfDoesNotHaveExpectedLength() throws Exception {
    ECDSAAlgorithm algorithm256 = (ECDSAAlgorithm) Algorithm.ECDSA256((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC"));
    byte[] joseSignature = new byte[32 * 2 - 1];
    exception.expect(SignatureException.class);
    exception.expectMessage("Invalid JOSE signature format.");

    algorithm256.JOSEToDER(joseSignature);
}
 
Example #20
Source Project: java-jwt   Author: auth0   File: ECDSAAlgorithmTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldPassECDSA256VerificationWithProvidedPublicKey() throws Exception {
    ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class);
    PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC");
    when(provider.getPublicKeyById("my-key-id")).thenReturn((ECPublicKey) publicKey);
    String jwt = "eyJhbGciOiJFUzI1NiIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.D_oU4CB0ZEsxHOjcWnmS3ZJvlTzm6WcGFx-HASxnvcB2Xu2WjI-axqXH9xKq45aPBDs330JpRhJmqBSc2K8MXQ";
    Algorithm algorithm = Algorithm.ECDSA256(provider);
    algorithm.verify(JWT.decode(jwt));
}
 
Example #21
Source Project: UAF   Author: eBay   File: KeyCodec.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public static byte[] getKeyAsRawBytes(
		org.bouncycastle.jce.interfaces.ECPublicKey pub) throws IOException {
	byte[] raw;
	ByteArrayOutputStream bos = new ByteArrayOutputStream(65);

	bos.write(0x04);
	bos.write(asUnsignedByteArray(pub.getQ().getX().toBigInteger()));
	bos.write(asUnsignedByteArray(pub.getQ().getY().toBigInteger()));
	raw = bos.toByteArray();
	logger.info("Raw key length:" + raw.length);
	return raw;
}
 
Example #22
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: ECDHCrypt.java    License: GNU General Public License v2.0 5 votes vote down vote up
ECDHCrypt(int curveId, SecureRandom random) {
    try {
        KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("EC");
        ECGenParameterSpec params =
                EllipticCurvesExtension.getECGenParamSpec(curveId);
        kpg.initialize(params, random);
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        publicKey = (ECPublicKey)kp.getPublic();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException("Could not generate DH keypair", e);
    }
}
 
Example #23
Source Project: ripple-lib-java   Author: ripple-unmaintained   File: KeyFactorySpi.java    License: ISC License 5 votes vote down vote up
protected Key engineTranslateKey(
    Key    key)
    throws InvalidKeyException
{
    if (key instanceof ECPublicKey)
    {
        return new BCECPublicKey((ECPublicKey)key, configuration);
    }
    else if (key instanceof ECPrivateKey)
    {
        return new BCECPrivateKey((ECPrivateKey)key, configuration);
    }

    throw new InvalidKeyException("key type unknown");
}
 
Example #24
Source Project: RipplePower   Author: cping   File: JCEECPublicKey.java    License: Apache License 2.0 5 votes vote down vote up
public JCEECPublicKey(
    ECPublicKey     key)
{
    this.algorithm = key.getAlgorithm();
    this.ecSpec = key.getParams();
    this.q = EC5Util.convertPoint(this.ecSpec, key.getW(), false);
}
 
Example #25
Source Project: swim   Author: swimos   File: JsonWebKeySpec.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void parseECPublicKey() {
  final ECPublicKey key = (ECPublicKey) JsonWebKey.parse("{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":\"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4\",\"y\":\"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM\",\"use\":\"enc\",\"kid\":\"1\"}").key();
  assertEquals(key.getW().getAffineX(), new BigInteger("21994169848703329112137818087919262246467304847122821377551355163096090930238"));
  assertEquals(key.getW().getAffineY(), new BigInteger("101451294974385619524093058399734017814808930032421185206609461750712400090915"));
  assertEquals(key.getParams(), JsonWebKey.p256);
}
 
Example #26
Source Project: RipplePower   Author: cping   File: BCECPublicKey.java    License: Apache License 2.0 5 votes vote down vote up
public BCECPublicKey(
    ECPublicKey key,
    ProviderConfiguration configuration)
{
    this.algorithm = key.getAlgorithm();
    this.ecSpec = key.getParams();
    this.q = EC5Util.convertPoint(this.ecSpec, key.getW(), false);
}
 
Example #27
Source Project: cxf   Author: apache   File: JwkUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static JsonWebKey fromECPublicKey(ECPublicKey pk, String curve, String kid) {
    JsonWebKey jwk = prepareECJwk(curve, kid);
    jwk.setProperty(JsonWebKey.EC_X_COORDINATE,
                    Base64UrlUtility.encode(pk.getW().getAffineX().toByteArray()));
    jwk.setProperty(JsonWebKey.EC_Y_COORDINATE,
                    Base64UrlUtility.encode(pk.getW().getAffineY().toByteArray()));
    return jwk;
}
 
Example #28
Source Project: javasdk   Author: hyperchain   File: ECKey.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private static ECPoint extractPublicKey(final ECPublicKey ecPublicKey) {
    final java.security.spec.ECPoint publicPointW = ecPublicKey.getW();
    final BigInteger xCoord = publicPointW.getAffineX();
    final BigInteger yCoord = publicPointW.getAffineY();

    return CURVE.getCurve().createPoint(xCoord, yCoord);
}
 
Example #29
Source Project: azure-keyvault-java   Author: Azure   File: EcKey.java    License: MIT License 5 votes vote down vote up
private JsonWebKeyCurveName getCurveFromKeyPair(KeyPair keyPair) {
	try {
		ECPublicKey key = (ECPublicKey) keyPair.getPublic();
		ECParameterSpec spec = key.getParams();
		EllipticCurve crv = spec.getCurve();
		
		List<JsonWebKeyCurveName> curveList = Arrays.asList(JsonWebKeyCurveName.P_256, JsonWebKeyCurveName.P_384, JsonWebKeyCurveName.P_521, JsonWebKeyCurveName.P_256K);
		
		for (JsonWebKeyCurveName curve : curveList) {
			ECGenParameterSpec gps = new ECGenParameterSpec(CURVE_TO_SPEC_NAME.get(curve));
			KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", _provider);
			kpg.initialize(gps);
			
			// Generate dummy keypair to get parameter spec.
			KeyPair apair = kpg.generateKeyPair();
			ECPublicKey apub = (ECPublicKey) apair.getPublic();
			ECParameterSpec aspec = apub.getParams();
			EllipticCurve acurve = aspec.getCurve();
			
			//Matches the parameter spec
			if (acurve.equals(crv)) {
				return curve;
			}
		}
		
		//Did not find a supported curve.
		throw new IllegalArgumentException ("Curve not supported.");
	} catch (GeneralSecurityException e) {
		throw new IllegalStateException(e);
	}
}
 
Example #30
Source Project: cwac-netsecurity   Author: commonsguy   File: CertificatePriorityComparator.java    License: Apache License 2.0 5 votes vote down vote up
private int getKeySize(PublicKey pkey) {
    if (pkey instanceof ECPublicKey) {
        return ((ECPublicKey) pkey).getParams().getCurve().getField().getFieldSize();
    } else if (pkey instanceof RSAPublicKey) {
        return ((RSAPublicKey) pkey).getModulus().bitLength();
    } else {
        throw new IllegalArgumentException(
                "Unsupported public key type: " + pkey.getClass().getName());
    }
}