Android 6.0密钥库ClassCast异常

时间:2016-05-31 19:11:19

标签: java android cryptography android-6.0-marshmallow java-security

我正在使用Qlassified library,并且我在Android 6.0和6.0.1上引发了以下异常: java.lang.ClassCastException: android.security.keystore.AndroidKeyStoreECPublicKey cannot be cast to java.security.interfaces.RSAPublicKey

具体而言,当在此代码块内加密数据时会发生这种情况:

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);

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这来自密钥库中存储的密钥的生成。您使用的是EC算法。您必须指定RSA算法,如下所示:

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

我遇到了同样的问题,这解决了它。