3

Yes this is a duplicate of this question. The answer to that is, however, wrong and misleading. The answer suggested writing the key to a file where other apps can access the file. If I'm not mistaken, the purpose of keystore is to generate and store private keys that can only be seen by your app, so I'm not even sure why the answer was accepted in that question.

Another question is about encryption and decryption but not really about saving the data to keystore.

Another one here might be what I'm looking for but if I'm not mistaken, CipherOutputStream is similar to FileOutputStream but it encrypts the data first before writing it. From the docs:

This class wraps an output stream and a cipher so that write methods send the data through the cipher before writing them to the underlying output stream.

What I want to know here is not the one generated using keytool (I'm guessing it is different, unless I'm wrong) but the one introduced in android 4.3. Either way, I want to learn to save private keys in keystore programmatically.

Aditional Info

Ok, so I found that you can automatically generate keys once you call the KeyPairGenerator as demonstrated in this app. But what I want to do is generate a key in my server (as my app is offline and will occasionally connect online), then save that key inside keystore as an entry. My problem now is creating entry then saving it. The reason for this is, I want to create one key like an api key for my app. If I use the key generated by keystore, it would have been different everytime I create it for different devices.

Community
  • 1
  • 1
hehe
  • 1,194
  • 10
  • 23

2 Answers2

0

For ages the keytool application shipped as part of Java could provide all the functionality to generate a private key and certificate sign request from a Java keystore, but the most basic function, importing a preexisting private key and certificate generated externally, remained overlooked.

This is fixed in Java 6, at long last.

The solution is to convert your existing certificate and key into a PKCS12 file, and then use the keytool functionality to merge one keystore with another one. Java 6 can treat a PKCS12 file as a keystore, so putting this together, you get this:

keytool -importkeystore -deststorepass changeit -destkeypass changeit
-destkeystore my-keystore.jks -srckeystore cert-and-key.p12 -srcstoretype PKCS12 -srcstorepass cert-and-key-password -alias 1

Refer this page for more details

  • Thanks for the answer. I'm guessing that is different from the one introduced in [android 4.3](http://developer.android.com/about/versions/android-4.3.html)? I think you use that one for signing your apk, am I right? – hehe Jan 14 '16 at 07:42
0

Try using Keystoreexplorer (a simple program) for managing your certificates and stores. First create it with keytool as @Androidmechanic suggegest, and then use keystoreexplorer for adding it to a keystore

Oldskultxo
  • 845
  • 6
  • 16