我正在关注这个教程:如何使用 Android Keystore 存储密码和其他敏感信息 http://www.androidauthority.com/use-android-keystore-store-passwords-sensitive-information-623779/。它(松散地)与 Google Sample 应用程序联系在一起:基本Android密钥库 http://developer.android.com/samples/BasicAndroidKeyStore/index.html.
我可以使用公钥加密我的数据,并且可以在运行 Lollipop 的设备上解密。但是,我有一台运行 Marshmallow 的 Nexus 6,并且崩溃并给出错误:
java.lang.RuntimeException: Unable to create application com.android.test: java.lang.ClassCastException: android.security.keystore.AndroidKeyStoreRSAPrivateKey cannot be cast to java.security.interfaces.RSAPrivateKey
这是它崩溃的代码:
KeyStore.Entry entry;
//Get Android KeyStore
ks = KeyStore.getInstance(KeystoreHelper.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
// Weird artifact of Java API. If you don't have an InputStream to load, you still need to call "load", or it'll crash.
ks.load(null);
// Load the key pair from the Android Key Store
entry = ks.getEntry(mAlias, null);
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) entry;
//ERROR OCCURS HERE::
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKeyEntry.getPrivateKey();
Cipher output = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
output.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
我不愿意将其归因于 Android M 的怪异,因为我看不出 Java 加密库会发生变化的原因。如果 M 版本发布并且我们的应用程序立即在 M 上崩溃,我将遇到大麻烦。
我做错了什么吗?该错误非常明确地表明您无法转换为 RSAPrivateKey,那么有人知道从条目中获取 RSAPrivateKey 的更好方法吗?
非常感谢。