Search in sources :

Example 11 with KeyStoreException

use of java.security.KeyStoreException in project OpenAttestation by OpenAttestation.

the class SslUtil method createX509TrustManagerWithCertificates.

public static X509TrustManager createX509TrustManagerWithCertificates(X509Certificate[] certificates) throws KeyManagementException {
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(createTrustedSslKeystore(certificates));
        TrustManager[] tms = tmf.getTrustManagers();
        for (TrustManager tm : tms) {
            if (tm instanceof X509TrustManager) {
                return (X509TrustManager) tm;
            }
        }
    } catch (NoSuchAlgorithmException e) {
        throw new KeyManagementException("Cannot create X509TrustManager", e);
    } catch (IOException e) {
        throw new KeyManagementException("Cannot create X509TrustManager", e);
    } catch (CertificateException e) {
        throw new KeyManagementException("Cannot create X509TrustManager", e);
    } catch (UnrecoverableEntryException e) {
        throw new KeyManagementException("Cannot create X509TrustManager", e);
    } catch (KeyStoreException e) {
        throw new KeyManagementException("Cannot create X509TrustManager", e);
    }
    throw new IllegalArgumentException("TrustManagerFactory did not return an X509TrustManager instance");
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) UnrecoverableEntryException(java.security.UnrecoverableEntryException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 12 with KeyStoreException

use of java.security.KeyStoreException in project android_frameworks_base by ParanoidAndroid.

the class AndroidKeyStore method setPrivateKeyEntry.

private void setPrivateKeyEntry(String alias, PrivateKey key, Certificate[] chain, KeyStoreParameter params) throws KeyStoreException {
    byte[] keyBytes = null;
    final String pkeyAlias;
    if (key instanceof OpenSSLKeyHolder) {
        pkeyAlias = ((OpenSSLKeyHolder) key).getOpenSSLKey().getAlias();
    } else {
        pkeyAlias = null;
    }
    final boolean shouldReplacePrivateKey;
    if (pkeyAlias != null && pkeyAlias.startsWith(Credentials.USER_PRIVATE_KEY)) {
        final String keySubalias = pkeyAlias.substring(Credentials.USER_PRIVATE_KEY.length());
        if (!alias.equals(keySubalias)) {
            throw new KeyStoreException("Can only replace keys with same alias: " + alias + " != " + keySubalias);
        }
        shouldReplacePrivateKey = false;
    } else {
        // Make sure the PrivateKey format is the one we support.
        final String keyFormat = key.getFormat();
        if ((keyFormat == null) || (!"PKCS#8".equals(keyFormat))) {
            throw new KeyStoreException("Only PrivateKeys that can be encoded into PKCS#8 are supported");
        }
        // Make sure we can actually encode the key.
        keyBytes = key.getEncoded();
        if (keyBytes == null) {
            throw new KeyStoreException("PrivateKey has no encoding");
        }
        shouldReplacePrivateKey = true;
    }
    // Make sure the chain exists since this is a PrivateKey
    if ((chain == null) || (chain.length == 0)) {
        throw new KeyStoreException("Must supply at least one Certificate with PrivateKey");
    }
    // Do chain type checking.
    X509Certificate[] x509chain = new X509Certificate[chain.length];
    for (int i = 0; i < chain.length; i++) {
        if (!"X.509".equals(chain[i].getType())) {
            throw new KeyStoreException("Certificates must be in X.509 format: invalid cert #" + i);
        }
        if (!(chain[i] instanceof X509Certificate)) {
            throw new KeyStoreException("Certificates must be in X.509 format: invalid cert #" + i);
        }
        x509chain[i] = (X509Certificate) chain[i];
    }
    final byte[] userCertBytes;
    try {
        userCertBytes = x509chain[0].getEncoded();
    } catch (CertificateEncodingException e) {
        throw new KeyStoreException("Couldn't encode certificate #1", e);
    }
    /*
         * If we have a chain, store it in the CA certificate slot for this
         * alias as concatenated DER-encoded certificates. These can be
         * deserialized by {@link CertificateFactory#generateCertificates}.
         */
    final byte[] chainBytes;
    if (chain.length > 1) {
        /*
             * The chain is passed in as {user_cert, ca_cert_1, ca_cert_2, ...}
             * so we only need the certificates starting at index 1.
             */
        final byte[][] certsBytes = new byte[x509chain.length - 1][];
        int totalCertLength = 0;
        for (int i = 0; i < certsBytes.length; i++) {
            try {
                certsBytes[i] = x509chain[i + 1].getEncoded();
                totalCertLength += certsBytes[i].length;
            } catch (CertificateEncodingException e) {
                throw new KeyStoreException("Can't encode Certificate #" + i, e);
            }
        }
        /*
             * Serialize this into one byte array so we can later call
             * CertificateFactory#generateCertificates to recover them.
             */
        chainBytes = new byte[totalCertLength];
        int outputOffset = 0;
        for (int i = 0; i < certsBytes.length; i++) {
            final int certLength = certsBytes[i].length;
            System.arraycopy(certsBytes[i], 0, chainBytes, outputOffset, certLength);
            outputOffset += certLength;
            certsBytes[i] = null;
        }
    } else {
        chainBytes = null;
    }
    /*
         * Make sure we clear out all the appropriate types before trying to
         * write.
         */
    if (shouldReplacePrivateKey) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
    } else {
        Credentials.deleteCertificateTypesForAlias(mKeyStore, alias);
    }
    final int flags = (params == null) ? 0 : params.getFlags();
    if (shouldReplacePrivateKey && !mKeyStore.importKey(Credentials.USER_PRIVATE_KEY + alias, keyBytes, android.security.KeyStore.UID_SELF, flags)) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
        throw new KeyStoreException("Couldn't put private key in keystore");
    } else if (!mKeyStore.put(Credentials.USER_CERTIFICATE + alias, userCertBytes, android.security.KeyStore.UID_SELF, flags)) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
        throw new KeyStoreException("Couldn't put certificate #1 in keystore");
    } else if (chainBytes != null && !mKeyStore.put(Credentials.CA_CERTIFICATE + alias, chainBytes, android.security.KeyStore.UID_SELF, flags)) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
        throw new KeyStoreException("Couldn't put certificate chain in keystore");
    }
}
Also used : OpenSSLKeyHolder(org.apache.harmony.xnet.provider.jsse.OpenSSLKeyHolder) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate)

Example 13 with KeyStoreException

use of java.security.KeyStoreException in project android_frameworks_base by ParanoidAndroid.

the class AndroidKeyStore method engineSetEntry.

@Override
public void engineSetEntry(String alias, Entry entry, ProtectionParameter param) throws KeyStoreException {
    if (entry == null) {
        throw new KeyStoreException("entry == null");
    }
    if (engineContainsAlias(alias)) {
        engineDeleteEntry(alias);
    }
    if (entry instanceof KeyStore.TrustedCertificateEntry) {
        KeyStore.TrustedCertificateEntry trE = (KeyStore.TrustedCertificateEntry) entry;
        engineSetCertificateEntry(alias, trE.getTrustedCertificate());
        return;
    }
    if (param != null && !(param instanceof KeyStoreParameter)) {
        throw new KeyStoreException("protParam should be android.security.KeyStoreParameter; was: " + param.getClass().getName());
    }
    if (entry instanceof PrivateKeyEntry) {
        PrivateKeyEntry prE = (PrivateKeyEntry) entry;
        setPrivateKeyEntry(alias, prE.getPrivateKey(), prE.getCertificateChain(), (KeyStoreParameter) param);
        return;
    }
    throw new KeyStoreException("Entry must be a PrivateKeyEntry or TrustedCertificateEntry; was " + entry);
}
Also used : KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry)

Example 14 with KeyStoreException

use of java.security.KeyStoreException in project android_frameworks_base by ParanoidAndroid.

the class AndroidKeyStoreTest method testKeyStore_SetKeyEntry_ProtectedKey_Encrypted_Failure.

public void testKeyStore_SetKeyEntry_ProtectedKey_Encrypted_Failure() throws Exception {
    setupPassword();
    mKeyStore.load(null, null);
    final CertificateFactory f = CertificateFactory.getInstance("X.509");
    final Certificate caCert = f.generateCertificate(new ByteArrayInputStream(FAKE_CA_1));
    KeyFactory keyFact = KeyFactory.getInstance("RSA");
    PrivateKey privKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(FAKE_KEY_1));
    final Certificate[] chain = new Certificate[2];
    chain[0] = f.generateCertificate(new ByteArrayInputStream(FAKE_USER_1));
    chain[1] = caCert;
    try {
        mKeyStore.setKeyEntry(TEST_ALIAS_1, privKey, "foo".toCharArray(), chain);
        fail("Should fail when a password is specified");
    } catch (KeyStoreException success) {
    }
}
Also used : RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) KeyStoreException(java.security.KeyStoreException) CertificateFactory(java.security.cert.CertificateFactory) KeyFactory(java.security.KeyFactory) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 15 with KeyStoreException

use of java.security.KeyStoreException in project android_frameworks_base by ParanoidAndroid.

the class AndroidKeyStoreTest method testKeyStore_SetEntry_PrivateKeyEntry_Params_Unencrypted_Failure.

public void testKeyStore_SetEntry_PrivateKeyEntry_Params_Unencrypted_Failure() throws Exception {
    mKeyStore.load(null, null);
    KeyFactory keyFact = KeyFactory.getInstance("RSA");
    PrivateKey expectedKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(FAKE_KEY_1));
    final CertificateFactory f = CertificateFactory.getInstance("X.509");
    final Certificate[] expectedChain = new Certificate[2];
    expectedChain[0] = f.generateCertificate(new ByteArrayInputStream(FAKE_USER_1));
    expectedChain[1] = f.generateCertificate(new ByteArrayInputStream(FAKE_CA_1));
    PrivateKeyEntry entry = new PrivateKeyEntry(expectedKey, expectedChain);
    try {
        mKeyStore.setEntry(TEST_ALIAS_1, entry, new KeyStoreParameter.Builder(getContext()).setEncryptionRequired(true).build());
        fail("Shouldn't be able to insert encrypted entry when KeyStore uninitialized");
    } catch (KeyStoreException expected) {
    }
    assertNull(mKeyStore.getEntry(TEST_ALIAS_1, null));
}
Also used : RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) KeyStoreException(java.security.KeyStoreException) CertificateFactory(java.security.cert.CertificateFactory) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) KeyFactory(java.security.KeyFactory) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

KeyStoreException (java.security.KeyStoreException)797 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)506 IOException (java.io.IOException)409 KeyStore (java.security.KeyStore)359 CertificateException (java.security.cert.CertificateException)353 UnrecoverableKeyException (java.security.UnrecoverableKeyException)194 X509Certificate (java.security.cert.X509Certificate)189 KeyManagementException (java.security.KeyManagementException)172 Certificate (java.security.cert.Certificate)132 InputStream (java.io.InputStream)103 SSLContext (javax.net.ssl.SSLContext)103 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)95 FileInputStream (java.io.FileInputStream)94 File (java.io.File)80 PrivateKey (java.security.PrivateKey)71 TrustManager (javax.net.ssl.TrustManager)70 FileNotFoundException (java.io.FileNotFoundException)61 ByteArrayInputStream (java.io.ByteArrayInputStream)58 CertificateFactory (java.security.cert.CertificateFactory)58 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)53