将 AndroidKeyStoreRSAPrivateKey 转换为 RSAPrivateKey 时发生崩溃

2024-01-09

我正在关注这个教程:如何使用 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 的更好方法吗?

非常感谢。


我设法通过从 Cipher.getInstance 中删除 Provider 来实现此工作not转换为 RSAprivateKey。

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

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

我不是 100% 但我认为原因是棉花糖从 OpenSSL 到 BoringSSL 的变化。https://developer.android.com/preview/behavior-changes.html#behavior-apache-http-client https://developer.android.com/preview/behavior-changes.html#behavior-apache-http-client

无论如何,以上方法适用于 M 及以下。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 AndroidKeyStoreRSAPrivateKey 转换为 RSAPrivateKey 时发生崩溃 的相关文章

随机推荐