Search code examples
javaandroidserializationkeystore

Can not serialize AndroidKeyStore to OutputStream


I'm trying to save an Android KeyStore object into a file in order to use the generated private key later. I need to do this because once the app is exited, the private key is erased. To do this, I'm writing a KeyStore object into an output stream as per this and this example. However, when I attempt to do so, I get the following error:

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

It occurs at 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);

Is this the best way to store my KeyStore object for later use? If so, how can I go about fixing the Can not serialize AndroidKeyStore to OutputStream error?

Thanks.


Solution

  • Android KeyStore is not the same as AndroidKeyStore.

    AndroidKeyStore is an Android component that can be used to securely generate and store your keys. See 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.

    The keys are persistent. Any key generarated into AndroidKeyStore will be present after application restart. This is the recommended way to store your keys

    Note that the keys are non-extractable. If you need to export the private key in some way, you will need to use an standard keystore file, not AndroidKeystore