Crash casting AndroidKeyStoreRSAPrivateKey to RSAPrivateKey

匆匆过客 提交于 2019-11-27 18:29:10

I managed to get this working by removing the Provider from Cipher.getInstance and not casting to a RSAprivateKey.

KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) entry;

Cipher output = Cipher.getInstance("RSA/ECB/PKCS1Padding");
output.init(Cipher.DECRYPT_MODE, privateKeyEntry.getPrivateKey());

I'm not 100% but I think the reason for this I believe is the change in marshmallow from OpenSSL to BoringSSL. https://developer.android.com/preview/behavior-changes.html#behavior-apache-http-client

Anyway, the above worked for M and below.

Issue

  1. We are trying to parse "java.security.PrivateKey to java.security.interfaces.RSAPrivateKey" & "java.security.PublicKey to java.security.interfaces.RSAPublicKey". That's why we are getting ClassCastException.

Solution

  1. We don't need to parse the key, we can directly use the "java.security.PrivateKey" & "java.security.PublicKey" for Encryption & Decryption.

Encryption

KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)entry; 
PublicKey publicKey = privateKeyEntry.getCertificate().getPublicKey(); // Don't TypeCast to RSAPublicKey

Decryption

KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)entry;
PrivateKey privateKey = privateKeyEntry.getPrivateKey(); // Don't TypeCast to RSAPrivateKey

I resolved this issue by also following this(apart from @James answer above): On Android 6.0 you should not use "AndroidOpenSSL" for cipher creation, it would fail with "Need RSA private or public key" at cipher init for decryption. Simply use Cipher.getInstance("RSA/ECB/PKCS1Padding") and it will work.

I havn't tried it but you should be able to cast the android.security.keystore.AndroidKeyStoreRSAPrivateKey to the following separately. These should be the interfaces you need:

  1. java.security.PrivateKey
  2. java.security.interfaces.RSAKey
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!