I am currently attempting to put together a functioning KeyStore implementation in my Android application. I am currently building against a minimum API of 18 so that I can fully take advantage of a private KeyStore
for my app. I am attempting to generate n
number of KeyPair
objects, and save them in the KeyStore
for later retrieval. I have looked at this question, however it seems a bit outdated (2012) and does not really answer anything all that well. Honestly, most of the questions I've found on Stack Overflow seem to be incredibly outdated, like here and here.
So my intended flow is this:
- Attempt to retrieve a public key from the certificate correllating with the appropriate alias.
- In the event that this public key is null, create a new key.
- Utilize
KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
- Generate the key pair.
Everything up to this point is very straight forward and works just fine. Next is where it gets hairy.
- Save the key pair. Initialize the KeyStore via
KeyStore.getInstance("AndroidKeyStore");
- Attempt to generate an
X509Certificate
through anX509V3CertificateGenerator
. This certificate is self signed. For the cert, I set the signature algorithm as"SHA1WithRSAEncryption"
. - Finally, call
keyStore.setKeyEntry
For this last step there seem to be two options:
keyStore.setKeyEntry(String alias, byte[] key, Certificate[] chain);
or
keyStore.setKeyEntry(String alias, Key key, char[] password, Certificate[] chain);
I started with the second of the two, but received java.security.KeyStoreException: entries cannot be protected with passwords
.... Okay, that's odd, why would there be a method that guarantees to throw an exception? Let's try door number 1.
At which point, when I call setKeyEntry, and pass keyPair.getPrivate().getEncoded() as the second argument, I receive java.security.KeyStoreException: Operation not supported because key encoding is unknown
from the system.
So I'm kind of at a loss. Encryption like this is relatively new to me, so I was hoping that someone could shed some light on the very confusing situation that is the Android KeyStore system.