I\'m following this tutorial: How to use the Android Keystore to store passwords and other sensitive information. It (loosely) ties up with the Google Sample app: BasicAndro
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:
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
Solution
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.