javaandroidcryptographykeystoresecret-key

KeyStore.store((KeyStore.LoadStoreParameter) FileOutputStream) throws a "cannot be cast" error in Android cryptography module


I have the following code to generate a KeyStore (in Java?) and save it in the internal memory within the current physical Android device:

KeyStore keyStore;

try {
    keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
} catch (KeyStoreException e) {
    e.printStackTrace();
    return;
}

try {
    FileInputStream fileInputStream = thisClass_Context.getApplicationContext().openFileInput("Subs2IPA_Crypto.keystore"); 
} catch (FileNotFoundException e) {
    e.printStackTrace();
    try {
        keyStore.load(null); 
        FileOutputStream fileOutputStream = thisClass_Context.openFileOutput("Subs2IPA_Crypto.keystore", Context.MODE_PRIVATE);          
        keyStore.store((KeyStore.LoadStoreParameter) fileOutputStream); 
        fileOutputStream.close();

Android Studio wont let me write the command that I have seen in other examples to store the KeyStore:

keyStore.store(fileOutputStream);

this throws an error saying that the argument must be of the type: LoadStoreParameter, and offers a solution of casting to that type:

keyStore.store((KeyStore.LoadStoreParameter) fileOutputStream); 

But if I actually run the App with that code, it then throws an error from the same line saying that it cannot cast to the proposed type:

java.lang.ClassCastException: java.io.FileInputStream cannot be cast to java.security.KeyStore$LoadStoreParameter

This error is also generated if I run the similar command:

keyStore.load((KeyStore.LoadStoreParameter) fileInputStream);

There must be something that I'm missing here, but I cannot find code examples with alternative code implementation. How can I solve this?

Also, I'm curious. Somebody suggested that I should just implement the Android KeyStore and not the Java one. I didn't know that they were actually different !!! What I obviously need is the implementation of the Android KeyStore. If you can point me to a good example with complete code, please let me know.

Gracias (Thanks).


Solution

  • The JavaDoc for KeyStore lists two different overloads of the store() method:

    You are trying to call it with an OutputStream only which matches neither variant.

    You can try to cast your OutputStream to KeyStore.LoadStoreParameter which will fail at runtime (because FileOutputStream does not implement KeyStore.LoadStoreParameter).

    Or you can change your call to add a password (as char[])