Java/Security/KeyStore

Материал из Java эксперт
Перейти к: навигация, поиск

Create a keystore with a self-signed certificate, using the keytool command

   
keytool -keystore mySrvKeystore -keypasswd 123456 -genkey -keyalg RSA -alias mycert





Exporting a Certificate to a File

   
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.security.KeyStore;
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";
    Certificate cert = keystore.getCertificate(alias);
    File file = null;
    byte[] buf = cert.getEncoded();
    FileOutputStream os = new FileOutputStream(file);
    os.write(buf);
    os.close();
    Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8"));
    wr.write(new sun.misc.BASE64Encoder().encode(buf));
    wr.flush();
  }
}





Import a key/certificate pair from a pkcs12 file into a regular JKS format keystore

  
// 
// Copyright (c) 1999 Jason Gilbert
// $Id: PKCS12Import.java,v 1.3 2004/05/09 20:32:49 gregwilkins Exp $
// 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
/**
 * This class can be used to import a key/certificate pair from a pkcs12 file
 * into a regular JKS format keystore for use with jetty and other java based
 * SSL applications, etc. 
 *<PRE>
 *    usage: java PKCS12Import {pkcs12file} [newjksfile]
 *</PRE>
 *
 * If you don"t supply newjksfile, newstore.jks will be used.  This can be an
 * existing JKS keystore.
 * <P>
 * Upon execution, you will be prompted for the password for the pkcs12 keystore
 * as well as the password for the jdk file.  After execution you should have a
 * JKS keystore file that contains the private key and certificate that were in
 * the pkcs12
 * <P>
 * You can generate a pkcs12 file from PEM encoded certificate and key files
 * using the following openssl command:
 * <PRE>
 *    openssl pkcs12 -export -out keystore.pkcs12 -in www.crt -inkey www.key
 * </PRE>
 * then run:
 * <PRE>
 *    java PKCS12Import keystore.pkcs12 keytore.jks
 * </PRE>
 *
 * @author Jason Gilbert &lt;jason@doozer.ru&gt;
 */
public class PKCS12Import
{
   public static void main(String[] args) throws Exception
   {
      if (args.length < 1) {
         System.err.println(
               "usage: java PKCS12Import {pkcs12file} [newjksfile]");
         System.exit(1);
      }
      File fileIn = new File(args[0]);
      File fileOut;
      if (args.length > 1) {
         fileOut = new File(args[1]);
      } else {
         fileOut = new File("newstore.jks");
      }
      if (!fileIn.canRead()) {
         System.err.println(
               "Unable to access input keystore: " + fileIn.getPath());
         System.exit(2);
      }
      if (fileOut.exists() && !fileOut.canWrite()) {
         System.err.println(
               "Output file is not writable: " + fileOut.getPath());
         System.exit(2);
      }
      KeyStore kspkcs12 = KeyStore.getInstance("pkcs12");
      KeyStore ksjks = KeyStore.getInstance("jks");
      System.out.print("Enter input keystore passphrase: ");
      char[] inphrase = readPassphrase();
      System.out.print("Enter output keystore passphrase: ");
      char[] outphrase = readPassphrase();
      kspkcs12.load(new FileInputStream(fileIn), inphrase);
      ksjks.load(
            (fileOut.exists())
            ? new FileInputStream(fileOut) : null, outphrase);
      Enumeration eAliases = kspkcs12.aliases();
      int n = 0;
      while (eAliases.hasMoreElements()) {
         String strAlias = (String)eAliases.nextElement();
         System.err.println("Alias " + n++ + ": " + strAlias);
         if (kspkcs12.isKeyEntry(strAlias)) {
            System.err.println("Adding key for alias " + strAlias);
            Key key = kspkcs12.getKey(strAlias, inphrase);
            Certificate[] chain = kspkcs12.getCertificateChain(strAlias);
            ksjks.setKeyEntry(strAlias, key, outphrase, chain);
         }
      }
      OutputStream out = new FileOutputStream(fileOut);
      ksjks.store(out, outphrase);
      out.close();
   }
   static void dumpChain(Certificate[] chain)
   {
      for (int i = 0; i < chain.length; i++) {
         Certificate cert = chain[i];
         if (cert instanceof X509Certificate) {
            X509Certificate x509 = (X509Certificate)chain[i];
            System.err.println("subject: " + x509.getSubjectDN());
            System.err.println("issuer: " + x509.getIssuerDN());
         }
      }
   }
   static char[] readPassphrase() throws IOException
   {
      InputStreamReader in = new InputStreamReader(System.in);
      char[] cbuf = new char[256];
      int i = 0;
readchars:
      while (i < cbuf.length) {
         char c = (char)in.read();
         switch (c) {
            case "\r":
               break readchars;
            case "\n":
               break readchars;
            default:
               cbuf[i++] = c;
         }
      }
      char[] phrase = new char[i];
      System.arraycopy(cbuf, 0, phrase, 0, i);
      return phrase;
   }
}





Listing the Aliases in a Key Store: A key store is a collection of keys and certificates.

   
import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Enumeration;
public class Main {
  public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("yourfile"+".keystore");
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    String password = "my-keystore-password";
    keystore.load(is, password.toCharArray());
    Enumeration e = keystore.aliases();
    for (; e.hasMoreElements();) {
      String alias = (String) e.nextElement();
      boolean b = keystore.isKeyEntry(alias);
      b = keystore.isCertificateEntry(alias);
    }
    is.close();
  }
}





Listing the Aliases in a Key Store using keytool:

   
keytool -list -storepass my-keystore-password





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);
    }
  }
}