2

I use this small snippet to store a KeyPair in Android's keystore :

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null);
Certificate[] cert = new Certificate[1];
cert[0] = getCertificate(kp);
ks.setKeyEntry(PRIVATE_KEY_TAG, kp.getPrivate(), null, cert);
ks.setKeyEntry(PUBLIC_KEY_TAG, kp.getPublic(), null, cert);

But when i fetch a key from KeyStore, with ks.getKey(PUBLIC_KEY_TAG, null).getEncoded(), i get this exception :

Attempt to invoke interface method Key.getEncoded() on a null object

And when i try to encrypt a String through a Cipher, i get a :

Unknow key type passed to RSA

Any idea on why this KeyStore is causing problems ? Thanks.

Rogue
  • 751
  • 1
  • 17
  • 36

1 Answers1

2

You can retrieve the public key from the certificate instead. Key stores can be used to store the private key / certificate you hold yourself, or a trusted certificate of another entity. Java (and Android) key stores are mainly targeted at X5.09 based PKI. Storing a public key with a certificate does not make sense, the public key is already contained within the certificate.

So instead try:

ks.getCertificate(PRIVATE_KEY_TAG).getPublicKey().getEncoded();
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • Yeah, but i still have to store the certificate, which is not working. And I still won't be able to get the private key from the certificate right ? – Rogue Dec 20 '14 at 20:30
  • YOu can store the private key and cert, get the cert and then get the public key. Just a second, I'll update... – Maarten Bodewes Dec 20 '14 at 20:32
  • That's a good optimization, however my problem is that i can't fetch anything from KeyStore, so i won't be able to fetch PrivateKey, any clue ? – Rogue Dec 20 '14 at 20:34
  • Yay, it's working this way, you rocks. I can't understand why this error occurs tho, but as long as it works... Thanks again ! – Rogue Dec 20 '14 at 20:47
  • Storing public keys is just not really supported. With `getKey` it looks for a private key with corresponding cert. – Maarten Bodewes Dec 20 '14 at 20:54
  • I see, it seems logical this way. Thanks ;) – Rogue Dec 20 '14 at 20:55
  • I'm getting this problem again, when i quit the application and start it back, it seems like KeyStore delete its content when app stop, is it possible ? – Rogue Dec 20 '14 at 21:40
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/67392/discussion-between-maarten-bodewes-owlstead-and-rogue). – Maarten Bodewes Dec 20 '14 at 21:41