Search in sources :

Example 91 with KeyFactory

use of java.security.KeyFactory in project j2objc by google.

the class KeyFactoryTest method testTranslateKey.

@SuppressWarnings("unchecked")
public void testTranslateKey() {
    KeyFactory factory = null;
    try {
        factory = KeyFactory.getInstance(TEST_KEYFACTORY_NAME);
    } catch (NoSuchAlgorithmException e) {
        fail("unexpected exception: " + e);
    }
    assertNotNull(factory);
    {
        Key[] keys = { new TestPrivateKey(), new TestPublicKey() };
        Class[] translated = { TestPublicKey.class, TestPrivateKey.class };
        for (int i = 0; i < keys.length; i++) {
            Key key = keys[i];
            Class translate = translated[i];
            try {
                Key translateKey = factory.translateKey(key);
                assertNotNull(translateKey);
                assertEquals(translate, translateKey.getClass());
            } catch (InvalidKeyException e) {
                fail("unexpected exception: " + e);
            }
        }
    }
    {
        Key[] keys = { new AnotherKey(), null };
        Class[] exceptions = { InvalidKeyException.class, NullPointerException.class };
        for (int i = 0; i < keys.length; i++) {
            Key key = keys[i];
            String message = "translateKey(" + (key == null ? "null" : key.toString()) + ")";
            exceptionThrown = false;
            try {
                factory.translateKey(key);
            } catch (Exception e) {
                checkException(message, e, exceptions[i]);
            } finally {
                checkException(message, null, exceptions[i]);
            }
        }
    }
}
Also used : NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) KeyFactory(java.security.KeyFactory) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvocationTargetException(java.lang.reflect.InvocationTargetException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 92 with KeyFactory

use of java.security.KeyFactory in project j2objc by google.

the class X509Key method buildX509Key.

/*
     * Factory interface, building the kind of key associated with this
     * specific algorithm ID or else returning this generic base class.
     * See the description above.
     */
static PublicKey buildX509Key(AlgorithmId algid, BitArray key) throws IOException, InvalidKeyException {
    /*
         * Use the algid and key parameters to produce the ASN.1 encoding
         * of the key, which will then be used as the input to the
         * key factory.
         */
    DerOutputStream x509EncodedKeyStream = new DerOutputStream();
    encode(x509EncodedKeyStream, algid, key);
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(x509EncodedKeyStream.toByteArray());
    try {
        // Instantiate the key factory of the appropriate algorithm
        KeyFactory keyFac = KeyFactory.getInstance(algid.getName());
        // Generate the public key
        return keyFac.generatePublic(x509KeySpec);
    } catch (NoSuchAlgorithmException e) {
    // Return generic X509Key with opaque key data (see below)
    } catch (InvalidKeySpecException e) {
        throw new InvalidKeyException(e.getMessage(), e);
    }
    /*
         * Try again using JDK1.1-style for backwards compatibility.
         */
    String classname = "";
    try {
        Properties props;
        String keytype;
        Provider sunProvider;
        sunProvider = Security.getProvider("SUN");
        if (sunProvider == null)
            throw new InstantiationException();
        classname = sunProvider.getProperty("PublicKey.X.509." + algid.getName());
        if (classname == null) {
            throw new InstantiationException();
        }
        Class keyClass = null;
        try {
            keyClass = Class.forName(classname);
        } catch (ClassNotFoundException e) {
            ClassLoader cl = ClassLoader.getSystemClassLoader();
            if (cl != null) {
                keyClass = cl.loadClass(classname);
            }
        }
        Object inst = null;
        X509Key result;
        if (keyClass != null)
            inst = keyClass.newInstance();
        if (inst instanceof X509Key) {
            result = (X509Key) inst;
            result.algid = algid;
            result.setKey(key);
            result.parseKeyBits();
            return result;
        }
    } catch (ClassNotFoundException e) {
    } catch (InstantiationException e) {
    } catch (IllegalAccessException e) {
        // this should not happen.
        throw new IOException(classname + " [internal error]");
    }
    X509Key result = new X509Key(algid, key);
    return result;
}
Also used : X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) Properties(java.util.Properties) Provider(java.security.Provider) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory)

Example 93 with KeyFactory

use of java.security.KeyFactory in project error-prone by google.

the class InsecureCipherModePositiveCases method keyOperations.

public void keyOperations(StringProvider provider) {
    KeyFactory keyFactory;
    KeyAgreement keyAgreement;
    KeyPairGenerator keyPairGenerator;
    final String dh = "DH";
    try {
        // BUG: Diagnostic contains: compile-time constant
        keyFactory = KeyFactory.getInstance(provider.get());
        // BUG: Diagnostic contains: Diffie-Hellman on prime fields
        keyFactory = KeyFactory.getInstance(dh);
        // BUG: Diagnostic contains: DSA
        keyAgreement = KeyAgreement.getInstance("DSA");
        // BUG: Diagnostic contains: compile-time constant
        keyAgreement = KeyAgreement.getInstance(provider.get());
        // BUG: Diagnostic contains: Diffie-Hellman on prime fields
        keyPairGenerator = KeyPairGenerator.getInstance(dh);
        // BUG: Diagnostic contains: compile-time constant
        keyPairGenerator = KeyPairGenerator.getInstance(provider.get());
    } catch (NoSuchAlgorithmException e) {
    // We don't handle any exception as this code is not meant to be executed.
    }
}
Also used : KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyAgreement(javax.crypto.KeyAgreement) KeyFactory(java.security.KeyFactory)

Example 94 with KeyFactory

use of java.security.KeyFactory in project wycheproof by google.

the class EcKeyTest method testEncodedPrivateKey.

public void testEncodedPrivateKey() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    keyGen.initialize(EcUtil.getNistP256Params());
    KeyPair keyPair = keyGen.generateKeyPair();
    ECPrivateKey priv = (ECPrivateKey) keyPair.getPrivate();
    byte[] encoded = priv.getEncoded();
    System.out.println("Encoded ECPrivateKey:" + TestUtil.bytesToHex(encoded));
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(encoded);
    KeyFactory kf = KeyFactory.getInstance("EC");
    ECPrivateKey decoded = (ECPrivateKey) kf.generatePrivate(spec);
    assertEquals(priv.getS(), decoded.getS());
    assertEquals(priv.getParams().getCofactor(), decoded.getParams().getCofactor());
    assertEquals(priv.getParams().getCurve(), decoded.getParams().getCurve());
    assertEquals(priv.getParams().getGenerator(), decoded.getParams().getGenerator());
    assertEquals(priv.getParams().getOrder(), decoded.getParams().getOrder());
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) KeyPair(java.security.KeyPair) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) KeyPairGenerator(java.security.KeyPairGenerator) KeyFactory(java.security.KeyFactory)

Example 95 with KeyFactory

use of java.security.KeyFactory 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)

Aggregations

KeyFactory (java.security.KeyFactory)407 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)180 PrivateKey (java.security.PrivateKey)177 PublicKey (java.security.PublicKey)120 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)114 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)113 CertificateFactory (java.security.cert.CertificateFactory)103 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)99 ByteArrayInputStream (java.io.ByteArrayInputStream)93 Certificate (java.security.cert.Certificate)89 X509Certificate (java.security.cert.X509Certificate)87 RSAPublicKeySpec (java.security.spec.RSAPublicKeySpec)60 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)59 Entry (java.security.KeyStore.Entry)53 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)53 IOException (java.io.IOException)47 BigInteger (java.math.BigInteger)45 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)43 RSAPublicKey (java.security.interfaces.RSAPublicKey)43 Signature (java.security.Signature)40