AndroidKeyStoreRSAPrivateKey无法强制转换为RSAPrivateKey

时间:2016-03-30 09:41:51

标签: android keystore keychain android-6.0-marshmallow android-keystore

当我们在一个加密的字符串上使用密钥链在android中提供的密钥应用解密时,我们在Marshmallow的Marshmallow版本中获得了Exception,它运行正常。例外是:

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

这是我的代码:

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

为什么我收到例外?

0 个答案:

没有答案