Retrieving a Key Pair from a Key Store

This example retrieves from a keystore, the private and public key associated with an alias. To load a keystore, see Listing the Aliases in a Key Store.
public KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) { try { // Get private key Key key = keystore.getKey(alias, password); if (key instanceof PrivateKey) { // Get certificate of public key java.security.cert.Certificate cert = keystore.getCertificate(alias); // Get public key PublicKey publicKey = cert.getPublicKey(); // Return a key pair return new KeyPair(publicKey, (PrivateKey)key); } } catch (UnrecoverableKeyException e) { } catch (NoSuchAlgorithmException e) { } catch (KeyStoreException e) { } return null; }

Comments

3 Mar 2010 - 5:09am by Anonymous (not verified)

Thank you for this neat code. You saved my day. Keep up good work.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.