andy9775
andy9775

Reputation: 364

Android 6.0 keystore ClassCast Exception

I'm using the Qlassified library and I'm getting the following exception being thrown on android 6.0 and 6.0.1: java.lang.ClassCastException: android.security.keystore.AndroidKeyStoreECPublicKey cannot be cast to java.security.interfaces.RSAPublicKey

Specifically, this happens when the data is being encrypted inside of this code block:

final KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStoreInstance.getEntry(alias, null);

final RSAPublicKey publicKey = (RSAPublicKey) privateKeyEntry.getCertificate().getPublicKey(); // error

byte[] dataBytes = input.getBytes(CHARSET);
Cipher cipher = Cipher.getInstance(ALGORITHM, ANDROID_MODE);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.encodeToString(cipher.doFinal(dataBytes), BASE64_MODE);

any thoughts?

Upvotes: 1

Views: 557

Answers (1)

This comes from the generation of keys stored on keystore. You were using an EC algorithm. You must specify RSA algorithm like this:

KeyPairGenerator generator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
                    generator.initialize(params);

I had the same problem and this solved it.

Upvotes: 1

Related Questions