I am developing my android app. I am trying to generate the X509Certificate instance from my certificate file stream, but get CertificateException
You are trying to read a PKCS#12 data structure as it was a X509 certificate. The PKCS#12 standard specifies a data structure which can bundle multiple certificates and private keys, optionally protected by a password.
In order to read the PKCS#12 data you need to load it with a KeyStore. This code snippet show how list all entries of the PCKS#12 file:
KeyStore keyStore = KeyStore.getInstance("PKCS12");
File p12File = GET_CERT();
FileInputStream fis = new FileInputStream(p12File);
BufferedInputStream bis = new BufferedInputStream(fis);
keyStore.load(bis, password.toCharArray()); // password is the PKCS#12 password. If there is no password, just pass null
Enumeration aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
/* Do something with the keystore entry */
}
KeyStore entries can be private key, with or without an associated certificate chain (i.e. a sequence of certificate from the root certificate to the certificate corresponding to the private key), or a trusted certificate. You can determine the entry type by the KeyStore.isKeyEntry
and KeyStore.isCertificateEntry
methods.
According to the KeyChain intent you gave, it seems you want to add a new trusted Root CA certificate in the key chain. Therefore I think you should list the certificate entries of the PKCS#12 file.
EDIT (12th nov 2013)
How to get a trusted certificate from the keystore:
String alias = aliases.nextElement();
if (keyStore.isCertificateEntry(alias)) { // keep only trusted cert entries
Certificate caCert = keyStore.getCertificate(alias)
byte[] extraCertificate = caCert.getEncoded();
Intent installIntent = KeyChain.createInstallIntent();
installIntent.putExtra(KeyChain.EXTRA_CERTIFICATE, extraCertificate);
installIntent.putExtra(KeyChain.EXTRA_NAME, MY_CERT);
startActivityForResult(installIntent, INSTALL_KEYCHAIN_CODE);
}