4

When we apply decryption on an encrypted string with a key provided by keychain in android we are getting Exception in Marshmallow version below Marshmallow it's working fine. The exception is:

android.security.keystore.AndroidKeyStoreRSAPrivateKey cannot be cast to java.security.interfaces.RSAPrivateKey

Here is my code:

 public void decryptString(String alias) 
 {
     try
    {
        KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);
        RSAPrivateKey privateKey = (RSAPrivateKey) privateKeyEntry.getPrivateKey();

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

        String cipherText = encryptedText.getText().toString();
        CipherInputStream cipherInputStream = new CipherInputStream(new ByteArrayInputStream(Base64.decode(cipherText, Base64.DEFAULT)), output);
        ArrayList<Byte> values = new ArrayList<>();
        int nextByte;
        while ((nextByte = cipherInputStream.read()) != -1) {
            values.add((byte)nextByte);
        }

        byte[] bytes = new byte[values.size()];
        for(int i = 0; i < bytes.length; i++) {
            bytes[i] = values.get(i).byteValue();
        }

        String finalText = new String(bytes, 0, bytes.length, "UTF-8");
        decryptedText.setText(finalText);

    } 
    catch (Exception e) {
        Toast.makeText(this, "Exception " + e.getMessage() + " occured", Toast.LENGTH_LONG).show();
        Log.e(TAG, Log.getStackTraceString(e));
    }
}

Why am I receiving the exception?

jww
  • 97,681
  • 90
  • 411
  • 885
Gurmeet Singh
  • 199
  • 10
  • Now open on AOSP: [Issue 205450: Crash casting AndroidKeyStoreRSAPrivateKey to RSAPrivateKey](https://code.google.com/p/android/issues/detail?id=205450). – jww Mar 30 '16 at 18:50
  • i have solved my problem . I have use these code to decrypt KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(KEY, null);; Cipher output = Cipher.getInstance("RSA/ECB/PKCS1Padding"); output.init(Cipher.DECRYPT_MODE, privateKeyEntry.getPrivateKey()); – Gurmeet Singh Mar 31 '16 at 11:04
  • @GurmeetSingh but what happens if you aren't specifying the provider type? – CQM Apr 21 '16 at 23:30
  • @CQM we can create Cipher instance by two ways: 1. public static final Cipher getInstance(String transformation, Provider provider) throws NoSuchAlgorithmException, NoSuchPaddingException { if (provider == null) { throw new IllegalArgumentException("provider == null"); } return getCipher(transformation, provider); } 2. public static final Cipher getInstance(String transformation) throws NoSuchAlgorithmException, NoSuchPaddingException { return getCipher(transformation, null); } – Gurmeet Singh Apr 22 '16 at 07:48

0 Answers0