How do I list / export private keys from a keystore?

后端 未结 9 614
轮回少年
轮回少年 2020-11-30 19:26

How do I list and export a private key from a keystore?

9条回答
  •  盖世英雄少女心
    2020-11-30 19:32

    A portion of code originally from Example Depot for listing all of the aliases in a key store:

        // Load input stream into keystore
        keystore.load(is, password.toCharArray());
    
        // List the aliases
        Enumeration aliases = keystore.aliases();
        for (; aliases.hasMoreElements(); ) {
            String alias = (String)aliases.nextElement();
    
            // Does alias refer to a private key?
            boolean b = keystore.isKeyEntry(alias);
    
            // Does alias refer to a trusted certificate?
            b = keystore.isCertificateEntry(alias);
        }
    

    The exporting of private keys came up on the Sun forums a couple of months ago, and u:turingcompleter came up with a DumpPrivateKey class to stitch into your app.

    import java.io.FileInputStream;
    import java.security.Key;
    import java.security.KeyStore;
    import sun.misc.BASE64Encoder;
    
    public class DumpPrivateKey {
         /**
         * Provides the missing functionality of keytool
         * that Apache needs for SSLCertificateKeyFile.
         *
         * @param args  
      *
    • [0] Keystore filename. *
    • [1] Keystore password. *
    • [2] alias *
    */ static public void main(String[] args) throws Exception { if(args.length < 3) { throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias,

    Note: this use Sun package, which is a "bad thing".
    If you can download apache commons code, here is a version which will compile without warning:

    javac -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey.java
    

    and will give the same result:

    import java.io.FileInputStream;
    import java.security.Key;
    import java.security.KeyStore;
    //import sun.misc.BASE64Encoder;
    import org.apache.commons.codec.binary.Base64;
    
    public class DumpPrivateKey {
         /**
         * Provides the missing functionality of keytool
         * that Apache needs for SSLCertificateKeyFile.
         *
         * @param args  
      *
    • [0] Keystore filename. *
    • [1] Keystore password. *
    • [2] alias *
    */ static public void main(String[] args) throws Exception { if(args.length < 3) { throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias,

    You can use it like so:

    java -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey $HOME/.keystore changeit tomcat
    

提交回复
热议问题