Search in sources :

Example 46 with KeyStoreException

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

the class Pkcs12 method setRsaCredentialX509.

/**
     * Replaces an existing keypair with the same alias or adds a new keypair
     * if one did not already exist.
     * 
     * The chain is optional and if provided it must be the certificates that
     * signed the credential's public key, in order, with the Root CA being LAST.
     * 
     * @param key
     * @param chain
     * @param alias 
     * @param keyPassword
     */
public void setRsaCredentialX509(RsaCredentialX509 key, X509Certificate[] chain, String alias, String keyPassword) throws KeyManagementException {
    try {
        List<String> aliases = Collections.list(keystore.aliases());
        if (aliases.contains(alias)) {
            keystore.deleteEntry(alias);
        }
        X509Certificate[] chain1;
        if (chain != null) {
            chain1 = new X509Certificate[chain.length + 1];
            chain1[0] = key.getCertificate();
            System.arraycopy(chain, 0, chain1, 1, chain.length);
        } else {
            chain1 = new X509Certificate[] { key.getCertificate() };
        }
        keystore.setKeyEntry(alias, key.getPrivateKey(), keyPassword.toCharArray(), chain1);
    } catch (KeyStoreException e) {
        throw new KeyManagementException("Cannot add credential", e);
    }
}
Also used : KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) KeyManagementException(java.security.KeyManagementException)

Example 47 with KeyStoreException

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

the class Pkcs12 method save.

/**
     * Saves the keystore to the resource passed in to the constructor.
     * 
     * @throws IOException if there was an error writing the keystore to the resource
     * @throws KeyStoreException if the keystore has not been initialized, or if the integrity check algorithm is not available, or if any certificates in the keystore could not be loaded
     */
public void save() throws IOException, KeyStoreException {
    try {
        OutputStream out = keystoreResource.getOutputStream();
        //, 
        keystore.store(out, keystorePassword.toCharArray());
        out.close();
    } catch (NoSuchAlgorithmException e) {
        // if the algorithm used to check the integrity of the keystore cannot be found
        throw new KeyStoreException(e);
    } catch (CertificateException e) {
        // if any certificates in the keystore could not be loaded
        throw new KeyStoreException(e);
    }
}
Also used : OutputStream(java.io.OutputStream) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException)

Example 48 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 49 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 50 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)

Aggregations

KeyStoreException (java.security.KeyStoreException)381 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)211 IOException (java.io.IOException)179 CertificateException (java.security.cert.CertificateException)148 KeyStore (java.security.KeyStore)141 X509Certificate (java.security.cert.X509Certificate)112 UnrecoverableKeyException (java.security.UnrecoverableKeyException)95 Certificate (java.security.cert.Certificate)73 KeyManagementException (java.security.KeyManagementException)69 CertificateFactory (java.security.cert.CertificateFactory)39 SSLContext (javax.net.ssl.SSLContext)38 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)38 InputStream (java.io.InputStream)37 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)37 PrivateKey (java.security.PrivateKey)35 ByteArrayInputStream (java.io.ByteArrayInputStream)33 InvalidKeyException (java.security.InvalidKeyException)33 FileNotFoundException (java.io.FileNotFoundException)32 TrustManager (javax.net.ssl.TrustManager)30 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)28