Retrieving a Key Pair from a Key Store : KeyStore « Security « Java






Retrieving a Key Pair from a Key Store

     

import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;

public class Main {
  public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("your.keystore");

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "my-keystore-password".toCharArray());

    String alias = "myalias";

    Key key = keystore.getKey(alias, "password".toCharArray());
    if (key instanceof PrivateKey) {
      // Get certificate of public key
      Certificate cert = keystore.getCertificate(alias);

      // Get public key
      PublicKey publicKey = cert.getPublicKey();

      // Return a key pair
      new KeyPair(publicKey, (PrivateKey) key);
    }
  }
}

   
    
    
    
    
  








Related examples in the same category

1.Exporting a Certificate to a File
2.Listing the Aliases in a Key Store: A key store is a collection of keys and certificates.
3.Listing the Aliases in a Key Store using keytool:
4.Create a keystore with a self-signed certificate, using the keytool command
5.Import a key/certificate pair from a pkcs12 file into a regular JKS format keystore
6.This program signs a certificate, using the private key of another certificate in a keystore.
7.This class imports a key and a certificate into a keystore