无法将 AndroidKeyStore 序列化为 OutputStream

Can not serialize AndroidKeyStore to OutputStream

我正在尝试将 Android KeyStore 对象保存到文件中,以便稍后使用生成的私钥。我需要这样做,因为一旦应用程序退出,私钥就会被删除。为此,我根据 this and KeyStore 对象写入输出流 例子。但是,当我尝试这样做时,出现以下错误:

java.lang.UnsupportedOperationException: Can not serialize AndroidKeyStore to OutputStream

发生在mKeyStore.store(keyStoreOutputStream, keyStorePassword);

mKeyStore = KeyStore.getInstance("AndroidKeyStore");
mSignature = Signature.getInstance("SHA256withECDSA");
mKeyStore.load(null);

// Generate private key
PrivateKey key = (PrivateKey) mKeyStore.getKey(KEY_NAME, null);
Certificate [] cert = mKeyStore.getCertificateChain(KEY_NAME);
char[] keyStorePassword = null;

// Store private key into mKeyStore
mKeyStore.setKeyEntry(KEY_NAME, key, null, cert);

// Save mKeyStore to outputstream
String filepath = activity.getFilesDir().getPath().toString() + "/keystore.ks";
try (FileOutputStream keyStoreOutputStream = new FileOutputStream(filepath)) {
    mKeyStore.store(keyStoreOutputStream, keyStorePassword);
}

mSignature.initSign(key);

这是存储我的 KeyStore 对象供以后使用的最佳方式吗?如果是这样,我该如何解决 Can not serialize AndroidKeyStore to OutputStream 错误?

谢谢。

Android KeyStoreAndroidKeyStore 不同。

AndroidKeyStore 是一个 Android 组件,可用于安全地生成和存储您的密钥。看 https://developer.android.com/training/articles/keystore

The Android Keystore system lets you store cryptographic keys in a container to make it more difficult to extract from the device. Once keys are in the keystore, they can be used for cryptographic operations with the key material remaining non-exportable.

密钥是持久的。在 AndroidKeyStore 中生成的任何密钥都将在应用程序重启后出现。这是存储密钥的推荐方式

请注意,密钥是不可提取的。如果您需要以某种方式导出私钥,则需要使用标准密钥库文件,而不是 AndroidKeystore