Retrieving a Key Pair from a Key Store - Java Security

Java examples for Security:Key

Description

Retrieving a Key Pair from a Key Store

Demo Code

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;

public class Main {
  public KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) {
    try {/*from   w w w . ja v  a2s .c  om*/
      // 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;
  }
}

Related Tutorials