0

I´m trying to save a .PFX certificate in to the Internar Storage of my application.

When I get de .pfx from asset or raw the InputStream obtained is good, and works fine. But if I store this InputStream on the Internar Storage (or on Sharedprefences) the .PFX no works...and get this error when load the keystore:

java.io.IOException: stream does not represent a PKCS12 key store

This code works, but I need store the cert on the memory and not get it from assets...:

InputStream is = AppConstants.appContext.getResources().openRawResource(R.raw.XXXX);

This is the code to save the .PFX:

InputStream is = AppConstants.appContext.getResources().openRawResource(R.raw.XXXX);
        String filename = "XXXX";
        String string = is.toString();
        FileOutputStream outputStream;
        try {
            outputStream = AppConstants.appContext.openFileOutput(filename, AppConstants.appContext.MODE_PRIVATE);
            outputStream.write(string.getBytes());
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

This is the code to load the stored .PFX:

String filename = Uri.parse(PFX_FILE).getLastPathSegment();
        File file = File.createTempFile(filename, null, AppConstants.appContext.getCacheDir());
keyStore.load(new FileInputStream(file), "xxxx".toCharArray());

How I can save certificates on Internal Memory?

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

0

You want to copy a file from assets to internal memory.

String string = is.toString();

That will not give you the contents of that file. Instead you have to make a loop where you read something from the input stream and write that to the output stream.

There are many examples on this site how to exactly do that.

greenapps
  • 11,154
  • 2
  • 16
  • 19
0

Init empty keystore:

KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(null, password);

Parse you certificate obtained from web service, retrieve X509Certificate and PrivateKey

Store it in keystore:

 keyStore.setKeyEntry(alias, privateKey, password, new X509Certificate []{certificate});

Save keyStore:

OutputStream outputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
keyStore.store(outputStream, password);

And later, when you need your saved keystore, laod it from file:

InputStream in;
try {
    in = context.openFileInput(filename);
    try {
        keyStore.load(in, password);
    } finally {
        in.close();
    }
Than
  • 2,759
  • 1
  • 20
  • 41
  • Hi Than, how can we store the content of .pfx file in Sqlite DB and get it installed after execute sql query on same? Because if I am storing byte[] of .pfx file in DB and get it later, it is not working. Please suggest. – Sanat Pandey Jan 14 '19 at 07:13
  • @SanatPandey You can store it in .PEM format as PEM is just a String – Than Jan 16 '19 at 11:21