Search in sources :

Example 1 with ECPublicKeySpec

use of java.security.spec.ECPublicKeySpec in project robovm by robovm.

the class OpenSSLECKeyFactory method engineTranslateKey.

@Override
protected Key engineTranslateKey(Key key) throws InvalidKeyException {
    if (key == null) {
        throw new InvalidKeyException("key == null");
    }
    if ((key instanceof OpenSSLECPublicKey) || (key instanceof OpenSSLECPrivateKey)) {
        return key;
    } else if (key instanceof ECPublicKey) {
        ECPublicKey ecKey = (ECPublicKey) key;
        ECPoint w = ecKey.getW();
        ECParameterSpec params = ecKey.getParams();
        try {
            return engineGeneratePublic(new ECPublicKeySpec(w, params));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if (key instanceof ECPrivateKey) {
        ECPrivateKey ecKey = (ECPrivateKey) key;
        BigInteger s = ecKey.getS();
        ECParameterSpec params = ecKey.getParams();
        try {
            return engineGeneratePrivate(new ECPrivateKeySpec(s, params));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if ((key instanceof PrivateKey) && ("PKCS#8".equals(key.getFormat()))) {
        byte[] encoded = key.getEncoded();
        if (encoded == null) {
            throw new InvalidKeyException("Key does not support encoding");
        }
        try {
            return engineGeneratePrivate(new PKCS8EncodedKeySpec(encoded));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if ((key instanceof PublicKey) && ("X.509".equals(key.getFormat()))) {
        byte[] encoded = key.getEncoded();
        if (encoded == null) {
            throw new InvalidKeyException("Key does not support encoding");
        }
        try {
            return engineGeneratePublic(new X509EncodedKeySpec(encoded));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else {
        throw new InvalidKeyException("Key must be EC public or private key; was " + key.getClass().getName());
    }
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) ECPrivateKeySpec(java.security.spec.ECPrivateKeySpec) PrivateKey(java.security.PrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) PublicKey(java.security.PublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) InvalidKeyException(java.security.InvalidKeyException) ECPoint(java.security.spec.ECPoint) ECPublicKeySpec(java.security.spec.ECPublicKeySpec) ECPublicKey(java.security.interfaces.ECPublicKey) ECParameterSpec(java.security.spec.ECParameterSpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) BigInteger(java.math.BigInteger) InvalidKeySpecException(java.security.spec.InvalidKeySpecException)

Example 2 with ECPublicKeySpec

use of java.security.spec.ECPublicKeySpec in project platform_frameworks_base by android.

the class AndroidKeyStoreKeyFactorySpi method engineGetKeySpec.

@Override
protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpecClass) throws InvalidKeySpecException {
    if (key == null) {
        throw new InvalidKeySpecException("key == null");
    } else if ((!(key instanceof AndroidKeyStorePrivateKey)) && (!(key instanceof AndroidKeyStorePublicKey))) {
        throw new InvalidKeySpecException("Unsupported key type: " + key.getClass().getName() + ". This KeyFactory supports only Android Keystore asymmetric keys");
    }
    if (keySpecClass == null) {
        throw new InvalidKeySpecException("keySpecClass == null");
    } else if (KeyInfo.class.equals(keySpecClass)) {
        if (!(key instanceof AndroidKeyStorePrivateKey)) {
            throw new InvalidKeySpecException("Unsupported key type: " + key.getClass().getName() + ". KeyInfo can be obtained only for Android Keystore private keys");
        }
        AndroidKeyStorePrivateKey keystorePrivateKey = (AndroidKeyStorePrivateKey) key;
        String keyAliasInKeystore = keystorePrivateKey.getAlias();
        String entryAlias;
        if (keyAliasInKeystore.startsWith(Credentials.USER_PRIVATE_KEY)) {
            entryAlias = keyAliasInKeystore.substring(Credentials.USER_PRIVATE_KEY.length());
        } else {
            throw new InvalidKeySpecException("Invalid key alias: " + keyAliasInKeystore);
        }
        @SuppressWarnings("unchecked") T result = (T) AndroidKeyStoreSecretKeyFactorySpi.getKeyInfo(mKeyStore, entryAlias, keyAliasInKeystore, keystorePrivateKey.getUid());
        return result;
    } else if (X509EncodedKeySpec.class.equals(keySpecClass)) {
        if (!(key instanceof AndroidKeyStorePublicKey)) {
            throw new InvalidKeySpecException("Unsupported key type: " + key.getClass().getName() + ". X509EncodedKeySpec can be obtained only for Android Keystore public" + " keys");
        }
        @SuppressWarnings("unchecked") T result = (T) new X509EncodedKeySpec(((AndroidKeyStorePublicKey) key).getEncoded());
        return result;
    } else if (PKCS8EncodedKeySpec.class.equals(keySpecClass)) {
        if (key instanceof AndroidKeyStorePrivateKey) {
            throw new InvalidKeySpecException("Key material export of Android Keystore private keys is not supported");
        } else {
            throw new InvalidKeySpecException("Cannot export key material of public key in PKCS#8 format." + " Only X.509 format (X509EncodedKeySpec) supported for public keys.");
        }
    } else if (RSAPublicKeySpec.class.equals(keySpecClass)) {
        if (key instanceof AndroidKeyStoreRSAPublicKey) {
            AndroidKeyStoreRSAPublicKey rsaKey = (AndroidKeyStoreRSAPublicKey) key;
            @SuppressWarnings("unchecked") T result = (T) new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent());
            return result;
        } else {
            throw new InvalidKeySpecException("Obtaining RSAPublicKeySpec not supported for " + key.getAlgorithm() + " " + ((key instanceof AndroidKeyStorePrivateKey) ? "private" : "public") + " key");
        }
    } else if (ECPublicKeySpec.class.equals(keySpecClass)) {
        if (key instanceof AndroidKeyStoreECPublicKey) {
            AndroidKeyStoreECPublicKey ecKey = (AndroidKeyStoreECPublicKey) key;
            @SuppressWarnings("unchecked") T result = (T) new ECPublicKeySpec(ecKey.getW(), ecKey.getParams());
            return result;
        } else {
            throw new InvalidKeySpecException("Obtaining ECPublicKeySpec not supported for " + key.getAlgorithm() + " " + ((key instanceof AndroidKeyStorePrivateKey) ? "private" : "public") + " key");
        }
    } else {
        throw new InvalidKeySpecException("Unsupported key spec: " + keySpecClass.getName());
    }
}
Also used : X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) ECPublicKeySpec(java.security.spec.ECPublicKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException)

Example 3 with ECPublicKeySpec

use of java.security.spec.ECPublicKeySpec in project wycheproof by google.

the class EcdhTest method testWrongOrder.

/**
   * This test modifies the order of group in the public key. A severe bug would be an
   * implementation that leaks information whether the private key is larger than the order given in
   * the public key. Also a severe bug would be to reduce the private key modulo the order given in
   * the public key parameters.
   */
// TODO(bleichen): This can be merged with testModifiedPublic once this is fixed.
@SuppressWarnings("InsecureCryptoUsage")
public void testWrongOrder(String algorithm, ECParameterSpec spec) throws Exception {
    KeyAgreement ka;
    try {
        ka = KeyAgreement.getInstance(algorithm);
    } catch (NoSuchAlgorithmException ex) {
        System.out.println("testWrongOrder: " + algorithm + " not supported");
        return;
    }
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    ECPrivateKey priv;
    ECPublicKey pub;
    try {
        keyGen.initialize(spec);
        priv = (ECPrivateKey) keyGen.generateKeyPair().getPrivate();
        pub = (ECPublicKey) keyGen.generateKeyPair().getPublic();
    } catch (GeneralSecurityException ex) {
        // This is OK, since not all provider support Brainpool curves
        System.out.println("testWrongOrder: could not generate keys for curve");
        return;
    }
    // Get the shared secret for the unmodified keys.
    ka.init(priv);
    ka.doPhase(pub, true);
    byte[] shared = ka.generateSecret();
    // Generate a modified public key.
    ECParameterSpec modifiedParams = new ECParameterSpec(spec.getCurve(), spec.getGenerator(), spec.getOrder().shiftRight(16), 1);
    ECPublicKeySpec modifiedPubSpec = new ECPublicKeySpec(pub.getW(), modifiedParams);
    KeyFactory kf = KeyFactory.getInstance("EC");
    ECPublicKey modifiedPub;
    try {
        modifiedPub = (ECPublicKey) kf.generatePublic(modifiedPubSpec);
    } catch (GeneralSecurityException ex) {
        // The provider does not support non-standard curves or did a validity check.
        // Both would be correct.
        System.out.println("testWrongOrder: can't modify order.");
        return;
    }
    byte[] shared2;
    try {
        ka.init(priv);
        ka.doPhase(modifiedPub, true);
        shared2 = ka.generateSecret();
    } catch (GeneralSecurityException ex) {
        // This is the expected behavior
        System.out.println("testWrongOrder:" + ex.toString());
        return;
    }
    // TODO(bleichen): Getting here is already a bug and we might flag this later.
    // At the moment we are only interested in really bad behavior of a library, that potentially
    // leaks the secret key. This is the case when the shared secrets are different, since this
    // suggests that the implementation reduces the multiplier modulo the given order of the curve
    // or some other behaviour that is dependent on the private key.
    // An attacker who can check whether a DH computation was done correctly or incorrectly because
    // of modular reduction, can determine the private key, either by a binary search or by trying
    // to guess the private key modulo some small "order".
    // BouncyCastle v.1.53 fails this test, and leaks the private key.
    System.out.println("Generated shared secret with a modified order:" + algorithm + "\n" + "expected:" + TestUtil.bytesToHex(shared) + " computed:" + TestUtil.bytesToHex(shared2));
    assertEquals("Algorithm:" + algorithm, TestUtil.bytesToHex(shared), TestUtil.bytesToHex(shared2));
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) ECPublicKey(java.security.interfaces.ECPublicKey) ECParameterSpec(java.security.spec.ECParameterSpec) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyPairGenerator(java.security.KeyPairGenerator) KeyAgreement(javax.crypto.KeyAgreement) ECPublicKeySpec(java.security.spec.ECPublicKeySpec) KeyFactory(java.security.KeyFactory)

Example 4 with ECPublicKeySpec

use of java.security.spec.ECPublicKeySpec in project wycheproof by google.

the class EcdsaTest method publicKey1.

public ECPublicKeySpec publicKey1() throws Exception {
    ECParameterSpec params = EcUtil.getNistP256Params();
    ECPoint w = new ECPoint(PubX, PubY);
    return new ECPublicKeySpec(w, params);
}
Also used : ECParameterSpec(java.security.spec.ECParameterSpec) ECPoint(java.security.spec.ECPoint) ECPublicKeySpec(java.security.spec.ECPublicKeySpec)

Example 5 with ECPublicKeySpec

use of java.security.spec.ECPublicKeySpec in project wycheproof by google.

the class EcUtil method getWeakPublicKey.

/**
   * Returns a weak public key of order 3 such that the public key point is on the curve specified
   * in ecParams. This method is used to check ECC implementations for missing step in the
   * verification of the public key. E.g. implementations of ECDH must verify that the public key
   * contains a point on the curve as well as public and secret key are using the same curve.
   *
   * @param ecParams the parameters of the key to attack. This must be a curve in Weierstrass form
   *     over a prime order field.
   * @return a weak EC group with a genrator of order 3.
   */
public static ECPublicKeySpec getWeakPublicKey(ECParameterSpec ecParams) throws GeneralSecurityException {
    EllipticCurve curve = ecParams.getCurve();
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    keyGen.initialize(ecParams);
    BigInteger p = getModulus(curve);
    BigInteger three = new BigInteger("3");
    while (true) {
        // Generate a point on the original curve
        KeyPair keyPair = keyGen.generateKeyPair();
        ECPublicKey pub = (ECPublicKey) keyPair.getPublic();
        ECPoint w = pub.getW();
        BigInteger x = w.getAffineX();
        BigInteger y = w.getAffineY();
        // Find the curve parameters a,b such that 3*w = infinity.
        // This is the case if the following equations are satisfied:
        //    3x == l^2 (mod p)
        //    l == (3x^2 + a) / 2*y (mod p)
        //    y^2 == x^3 + ax + b (mod p)
        BigInteger l;
        try {
            l = modSqrt(x.multiply(three), p);
        } catch (GeneralSecurityException ex) {
            continue;
        }
        BigInteger xSqr = x.multiply(x).mod(p);
        BigInteger a = l.multiply(y.add(y)).subtract(xSqr.multiply(three)).mod(p);
        BigInteger b = y.multiply(y).subtract(x.multiply(xSqr.add(a))).mod(p);
        EllipticCurve newCurve = new EllipticCurve(curve.getField(), a, b);
        // Just a sanity check.
        checkPointOnCurve(w, newCurve);
        // Cofactor and order are of course wrong.
        ECParameterSpec spec = new ECParameterSpec(newCurve, w, p, 1);
        return new ECPublicKeySpec(w, spec);
    }
}
Also used : KeyPair(java.security.KeyPair) ECPublicKey(java.security.interfaces.ECPublicKey) EllipticCurve(java.security.spec.EllipticCurve) ECParameterSpec(java.security.spec.ECParameterSpec) GeneralSecurityException(java.security.GeneralSecurityException) BigInteger(java.math.BigInteger) KeyPairGenerator(java.security.KeyPairGenerator) ECPoint(java.security.spec.ECPoint) ECPublicKeySpec(java.security.spec.ECPublicKeySpec)

Aggregations

ECPublicKeySpec (java.security.spec.ECPublicKeySpec)14 ECParameterSpec (java.security.spec.ECParameterSpec)8 ECPoint (java.security.spec.ECPoint)6 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)6 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)6 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)6 RSAPublicKeySpec (java.security.spec.RSAPublicKeySpec)5 ECPublicKey (java.security.interfaces.ECPublicKey)4 BigInteger (java.math.BigInteger)3 GeneralSecurityException (java.security.GeneralSecurityException)3 KeyPairGenerator (java.security.KeyPairGenerator)3 ECPrivateKey (java.security.interfaces.ECPrivateKey)3 EllipticCurve (java.security.spec.EllipticCurve)3 KeyFactory (java.security.KeyFactory)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 PublicKey (java.security.PublicKey)2 ECFieldF2m (java.security.spec.ECFieldF2m)2 KeyAgreement (javax.crypto.KeyAgreement)2 AlgorithmParameters (java.security.AlgorithmParameters)1 InvalidKeyException (java.security.InvalidKeyException)1