java.security.interfaces.ECPublicKey Java Examples

The following examples show how to use java.security.interfaces.ECPublicKey. 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: BaseTestSupport.java    From termd with 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 #2
Source File: ECDSABouncyCastleProviderTests.java    From java-jwt with 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 #3
Source File: CSignature.java    From jdk8u_jdk with 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 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 #5
Source File: ECDSAAlgorithmTest.java    From java-jwt with 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 #6
Source File: P11ECDHKeyAgreement.java    From jdk8u-jdk with 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 #7
Source File: ECKeyTest.java    From azure-keyvault-java with 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 #8
Source File: ECDSABouncyCastleProviderTests.java    From java-jwt with 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 #9
Source File: ClientHandshaker.java    From jdk8u60 with 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 #10
Source File: P11ECDHKeyAgreement.java    From openjdk-jdk8u with 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 #11
Source File: ECKey.java    From tron-wallet-android with 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 #12
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 #13
Source File: ClientHandshaker.java    From openjdk-jdk8u-backup with 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 #14
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 #15
Source File: ECSignerTest.java    From fusionauth-jwt with 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 #16
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 #17
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 #18
Source File: ECDSAAlgorithmTest.java    From java-jwt with 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 #19
Source File: ECDHCrypt.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
ECDHCrypt(String curveName, SecureRandom random) {
    try {
        KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("EC");
        ECGenParameterSpec params = new ECGenParameterSpec(curveName);
        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 #20
Source File: JsonWebKeySpec.java    From swim with 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 #21
Source File: EcKey.java    From azure-keyvault-java with 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 #22
Source File: DOMKeyValue.java    From openjdk-jdk8u-backup 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();
    try {
        AccessController.doPrivileged(
            new PrivilegedExceptionAction<Void>() {
                public Void run() throws
                    ClassNotFoundException, NoSuchMethodException
                {
                    getMethods();
                    return null;
                }
            }
        );
    } catch (PrivilegedActionException pae) {
        throw new KeyException("ECKeyValue not supported",
                                pae.getException());
    }
    Object[] args = new Object[] { ecPoint, ecParams.getCurve() };
    try {
        ecPublicKey = (byte[])encodePoint.invoke(null, args);
    } catch (IllegalAccessException iae) {
        throw new KeyException(iae);
    } catch (InvocationTargetException ite) {
        throw new KeyException(ite);
    }
}
 
Example #23
Source File: KeyStoresTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void obtainCertificate(String keyAlgorithmName, int keySize, String domainName, String alias, KeyStore keyStore) throws Exception {
    try {
        ModelNode operation = new ModelNode();
        operation.get(ClientConstants.OP_ADDR).add("subsystem", "elytron").add("key-store", KEYSTORE_NAME);
        operation.get(ClientConstants.OP).set(ElytronDescriptionConstants.OBTAIN_CERTIFICATE);
        operation.get(ElytronDescriptionConstants.ALIAS).set(alias);
        operation.get(ElytronDescriptionConstants.DOMAIN_NAMES).add(domainName);
        operation.get(ElytronDescriptionConstants.AGREE_TO_TERMS_OF_SERVICE).set(true);
        operation.get(CredentialReference.CREDENTIAL_REFERENCE).get(CredentialReference.CLEAR_TEXT).set(KEY_PASSWORD);
        operation.get(ElytronDescriptionConstants.ALGORITHM).set(keyAlgorithmName);
        operation.get(ElytronDescriptionConstants.KEY_SIZE).set(keySize);
        operation.get(ElytronDescriptionConstants.CERTIFICATE_AUTHORITY_ACCOUNT).set(CERTIFICATE_AUTHORITY_ACCOUNT_NAME);
        assertSuccess(services.executeOperation(operation));
        assertTrue(keyStore.containsAlias(alias));
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, KEY_PASSWORD.toCharArray());
        X509Certificate signedCert = (X509Certificate) keyStore.getCertificate(alias);
        assertEquals(keyAlgorithmName, privateKey.getAlgorithm());
        assertEquals(keyAlgorithmName, signedCert.getPublicKey().getAlgorithm());
        if (keyAlgorithmName.equals("EC")) {
            assertEquals(keySize, ((ECPublicKey) signedCert.getPublicKey()).getParams().getCurve().getField().getFieldSize());
        } else if (keyAlgorithmName.equals("RSA")) {
            assertEquals(keySize, ((RSAPublicKey) signedCert.getPublicKey()).getModulus().bitLength());
        }
    } finally {
        removeCertificateAuthorityAccount();
        removeCertificateAuthority();
        removeKeyStore(ACCOUNTS_KEYSTORE_NAME);
        removeKeyStore(KEYSTORE_NAME);
    }
}
 
Example #24
Source File: JCEECPublicKey.java    From ripple-lib-java with ISC License 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 File: BCECPublicKey.java    From RipplePower with 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 #26
Source File: ECDHCrypt.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
ECDHCrypt(ECParameterSpec params, SecureRandom random) {
    try {
        KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("EC");
        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 #27
Source File: ECDHCrypt.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
ECDHCrypt(ECParameterSpec params, SecureRandom random) {
    try {
        KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("EC");
        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 #28
Source File: JCEECPublicKey.java    From RipplePower with 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 #29
Source File: BCDSTU4145PublicKey.java    From ripple-lib-java with ISC License 5 votes vote down vote up
public BCDSTU4145PublicKey(
    ECPublicKey key)
{
    this.algorithm = key.getAlgorithm();
    this.ecSpec = key.getParams();
    this.q = EC5Util.convertPoint(this.ecSpec, key.getW(), false);
}
 
Example #30
Source File: SecurityHelper.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
public static Cipher newECEncryptCipher(ECPublicKey publicKey) {
    try {
        return newECCipher(Cipher.ENCRYPT_MODE, publicKey);
    } catch (SecurityException e) {
        throw new InternalError(e);
    }
}