How to export private key from a keystore of self-signed certificate

前端 未结 4 1035
-上瘾入骨i
-上瘾入骨i 2020-12-08 07:44

I just created a self-signed certificate on a linux box running tomcat 6.

I created the keys like this, valid for 10 years:

keytool -genkey -alias to         


        
4条回答
  •  再見小時候
    2020-12-08 08:27

    http://anandsekar.github.io/exporting-the-private-key-from-a-jks-keystore/

    public class ExportPrivateKey {
            private File keystoreFile;
            private String keyStoreType;
            private char[] password;
            private String alias;
            private File exportedFile;
    
            public static KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) {
                    try {
                            Key key=keystore.getKey(alias,password);
                            if(key instanceof PrivateKey) {
                                    Certificate cert=keystore.getCertificate(alias);
                                    PublicKey publicKey=cert.getPublicKey();
                                    return new KeyPair(publicKey,(PrivateKey)key);
                            }
                    } catch (UnrecoverableKeyException e) {
            } catch (NoSuchAlgorithmException e) {
            } catch (KeyStoreException e) {
            }
            return null;
            }
    
            public void export() throws Exception{
                    KeyStore keystore=KeyStore.getInstance(keyStoreType);
                    BASE64Encoder encoder=new BASE64Encoder();
                    keystore.load(new FileInputStream(keystoreFile),password);
                    KeyPair keyPair=getPrivateKey(keystore,alias,password);
                    PrivateKey privateKey=keyPair.getPrivate();
                    String encoded=encoder.encode(privateKey.getEncoded());
                    FileWriter fw=new FileWriter(exportedFile);
                    fw.write(“—–BEGIN PRIVATE KEY—–\n“);
                    fw.write(encoded);
                    fw.write(“\n“);
                    fw.write(“—–END PRIVATE KEY—–”);
                    fw.close();
            }
    
    
            public static void main(String args[]) throws Exception{
                    ExportPrivateKey export=new ExportPrivateKey();
                    export.keystoreFile=new File(args[0]);
                    export.keyStoreType=args[1];
                    export.password=args[2].toCharArray();
                    export.alias=args[3];
                    export.exportedFile=new File(args[4]);
                    export.export();
            }
    }
    

提交回复
热议问题